Reputation: 87
I have two futures that I can await. However, I only want to wait for the first of the two to finish, and do other things as soon as that happens. Is there a way?
Thanks in advance!
Upvotes: 0
Views: 333
Reputation: 9924
futures_util::future::select
does exactly what you're looking for. Example:
match future::select(future1, future2).await {
Either::Left((value1, future2)) => todo!("do something with value1"),
Either::Right((value2, future1)) => todo!("do something with value2"),
};
tokio::select
is also relevant, but has some additional complexity.
Upvotes: 1
Reputation: 1808
Try this method,
function asyncTask1() {
return new <MethodName>(resolve => {
setTimeout(() => {
console.log("Async Task 1 completed");
resolve("Result, Async Task 1");
}, <mention time>);
});
}
This method help to wait the task to complete one by one.
<MethodName>.race([asyncTask1(), asyncTask2(),asyncTask3(),...])
.then(result => {
console.log("First task completed", result);
})
.catch(error => {
console.error("An error occurred:", error);
});
Upvotes: -1