How do i run a future without awaiting it? (in rust)
11:20 20 Jul 2022

I have some async function

async fn get_player(name: String, i: Instant) -> Option {
// some code here that returns a player structs
}

in my main function i want to run the above function concurrently in a loop, this function takes about 1sec to complete and I need to run it at least 50 times, hence I would like to make it concurrently run this function 50 times. in my main function i have a lazy_static custom Client struct which should not be created more than once.

main function

#[tokio::main]
async fn main() {
    client.init().await;

    println!("start");
    for i in 0..10 {
        println!("{}", i);
        let now = Instant::now();

        tokio::spawn(async move  {
            client.get_player("jay".to_string(), now).await;
        });
    }
    loop {}
}

the reason I am passing instant is because in my get_player function i have a println!() that just prints the execution time.

the above main method takes around 500ms for each function call, however the below code only takes 100ms.

#[tokio::main]
async fn maain(){
    client.init().await;

    for i in 0..10 {
        let now = Instant::now();
        client.get_player("jay".to_string(), now).await.expect("panic");
    }
}

but this function is still synchronous code, how do I actually run the async function concurrently without the time cost?

  • To better understand what am after is an implemention similar to this (its in java btw),
     CompleteableFuture.thenAccept(x -> x.SayHello(););

or in Js its something like .then after an async function.

is there any similar implementation in rust?

rust rust-tokio rust-async-std