How to execute multiple async functions at once and get the results?

Ale*_*aev 5 rust async-await rust-tokio

I have tried Tokio tasks, but there are no working examples to execute multiple tasks at once. What is wrong with this code?

fn main() {
    block_on(speak());
}

async fn speak() {
    let hold = vec![say(), greet()];
    let results = join_all(hold).await;
}

async fn say() {
    println!("hello");
}

async fn greet() {
    println!("world");
}
Run Code Online (Sandbox Code Playgroud)

here is the compiler output

error[E0308]: mismatched types
  --> sync\src\main.rs:14:27
   |
14 |     let hold = vec![say(),greet()];
   |                           ^^^^^^^ expected opaque type, found a different opaque type
...
23 | async fn greet(){
   |                 - the `Output` of this `async fn`'s found opaque type
   |
   = note:     expected type `impl core::future::future::Future` (opaque type at <sync\src\main.rs:19:15>)
           found opaque type `impl core::future::future::Future` (opaque type at <sync\src\main.rs:23:17>)
   = note: distinct uses of `impl Trait` result in different opaque types
Run Code Online (Sandbox Code Playgroud)

She*_*ter 7

对于两个期货,就像你一样,使用 future::join

use futures::{executor, future}; // 0.3.5

async fn speak() {
    let (_s, _g) = future::join(say(), greet()).await;
}
Run Code Online (Sandbox Code Playgroud)

有三个、四个和五个输入期货的变体:join3join4join5

还有try_join(和try_join3, try_join4, try_join5) 用于当您的未来返回 a 时Result

join是另一种处理要加入的静态数量期货的方法。

如果您需要支持动态数量的期货,您可以使用future::join_all(或try_join_all),但您必须拥有所有一种的向量。这是最简单的FutureExt::boxed(或FutureExt::boxed_local):

use futures::{executor, future, FutureExt}; // 0.3.5

async fn speak() {
    let futures = vec![say().boxed(), greet().boxed()];
    let _results = future::join_all(futures).await;
}
Run Code Online (Sandbox Code Playgroud)

请注意,此代码可以同时运行期货,但不会并行运行它们。对于并行执行,您需要引入某种任务。

也可以看看: