ASYNCHRONOUS RUST

 ASYNCHRONOUS RUST

  • Rust supports async/await like many other languages.
  • First you need to go to crates.io and search for futures.
  • Copy the futures library version, add it into Cago.toml and run your project.
  • futures = "0.3.25"
  • use futures:executor::block_on;
    
    async fn get_name() -> String{
      "Sanu Shilshad".to_string()
    }
    
    fn main(){
     let name: String = block_on(get_name());
     println!("Hello {}", name);
    }
  • 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}
    }
  • In the above example you can see that the value from the async block can be used outside the block by adding the keyword move after aync.

Comments