I want to run multiple async functions synchronously. I build a simple example for my problem. sleep1 should be executed at the beginning, but its requiered at a later point. sleep2 and sleep_arr should be executed before. Right now the code takes 8 seconds to complete but it should only take 5.
async fn test() -> bool {
let sleep1 = sleep(5);
let sleep2 = sleep(1).await;
let sleep_arr = vec![sleep(2), sleep(2)];
join_all(sleep_arr).await;
sleep1.await;
return true;
}
async fn sleep(sec: u64) -> () {
use async_std::task;
task::sleep(std::time::Duration::from_secs(sec)).await;
}
sleep(5)starts getting executed in line 1. It doesn't. Rust asyncs are lazy and only start once they get awaited. So thesleep(5)only starts to get executed atsleep1.await.