How to wait for a list of async function calls in rust?

喜你入骨 提交于 2020-08-20 12:01:31

问题


I have a list of async functions in rust that I want to execute concurrently and then wait for all them to finish. The working code I have right now is

 async fn start_consumers(&self) {
    for consumer in &self.consumers {
        consumer.consume().await;
    }
}

This is not quite accurate as the functions are executed serially. I am looking for something like join!, but which works on a dynamic vector, Using which I should be able to write something like

 async fn start_consumers(&self) {
    let mut v = Vec::new();
    for consumer in &self.consumers {
        consumer.consume();
    }
    join!(v);
}

Right now join! supports only tuples. I am looking for an alternative for that. Something similar to Promise.all() in JavaScript.


回答1:


I also asked a similar question on the same day, but in my case I had a Result wrapped in a Future. So instead of join_all I had to use try_join_all




回答2:


So after some searching I found that rust futures has a function called join_all which allows for waiting on a collection of futures.

 use futures::future::join_all;
 ....

 async fn start_consumers(&self) {
    let mut v = Vec::new();
    for consumer in &self.consumers {
        v.push(consumer.consume());
    }
    join_all(v).await;
 }


来源:https://stackoverflow.com/questions/63326882/how-to-wait-for-a-list-of-async-function-calls-in-rust

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!