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;
}
>Solution :
You can create an async block for the second sequence and then execute the two sequences that need to be executed in parallel using futures::join!:
async fn test() -> bool {
let sleep1 = sleep(5);
let task2 = async {
let sleep2 = sleep(1).await;
let sleep_arr = vec![sleep(2), sleep(2)];
futures::future::join_all(sleep_arr).await;
};
futures::join!(sleep1, task2);
return true;
}
async fn sleep(sec: u64) -> () {
tokio::time::sleep(std::time::Duration::from_secs(sec)).await;
}
#[tokio::main]
async fn main() {
let instant = std::time::Instant::now();
test().await;
dbg!(instant.elapsed());
}
Output:
[src/main.rs:20] instant.elapsed() = 5.001728234s
(I switched to tokio so it works in the playground but it should be the same with async_std.)