- The above code block shows a basic example of an async function.
- You can use await instead of block_on function, for that you will need to add another library called tokio, an advanced package of futures which provides additional functionality.
- You will need to add tokio from crates.io, like you did for futures.
tokio= { version = "1.22.0", features = ["full"] }
use tokio::time::{sleep, Duration};
async fn call_api_one() -> String{
sleep(Duration::from_secs(3)).await;
"One".to_string()
}
async fn call_api_two() -> String{
sleep(Duration::from_secs(3)).await;
"Two".to_string()
}
#[tokio::main]
async fn main(){
let one: String = call_api_one().await;
println!("Hello {}", one);
let two: String = call_api_two().await;
println!("Hello {}", two);
}
- In the above example, your program is awaiting for the completion of call_api_one function before running the function fn_call_api_two.
use tokio::time::{sleep, Duration};
use futures::Future;
fn call_api_one() -> impl Future<Output = String>{
async {
sleep(Duration::from_secs(3)).await;
"One".to_string()
}
}
fn call_api_two() -> impl Future<Output = String>{
async {
sleep(Duration::from_secs(3)).await;
"Two".to_string()
}
}
#[tokio::main]
async fn main(){
let one: String = call_api_one().await;
println!("Hello {}", one);
let two: String = call_api_two().await;
println!("Hello {}", two);
}
- In the above example we are using the trait Future to rewrite the code.
use tokio::time::{sleep, Duration};
use futures::Future;
fn call_async_name() -> impl Future<Output = String>{
let name: String = "Sanu".to_string();
async move{ format!("Hello {} Shilshad", name}
}
Comments
Post a Comment