如何一次执行多个异步功能并获得结果?

问题描述

我已经尝试了Tokio任务,但是没有可以同时执行多个任务的示例。此代码有什么问题?

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");
}

这是编译器的输出

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

解决方法

对于两个期货,如您所愿,请使用future::join

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

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

有三种,四种和五种输入期货的变体:join3join4join5

当您的未来返回Result时,还有try_join(和try_join3try_join4try_join5)。

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;
}

请注意,此代码可以同时运行期货,但不能并行运行。对于并行执行,您需要引入一些任务。

另请参阅:

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...