Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/visual-studio-code/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asynchronous 如何等待所有派生的异步任务_Asynchronous_Rust_Runtime_Future - Fatal编程技术网

Asynchronous 如何等待所有派生的异步任务

Asynchronous 如何等待所有派生的异步任务,asynchronous,rust,runtime,future,Asynchronous,Rust,Runtime,Future,我有一个异步方法,它使用tokio::fs浏览目录: use failure::Error; use futures::Future; use std::path::PathBuf; use tokio::prelude::*; fn visit_async(path: PathBuf) -> Box<Future<Item = (), Error = Error> + Send> { let task = tokio::fs::read_dir(path

我有一个异步方法,它使用
tokio::fs
浏览目录:

use failure::Error;
use futures::Future;
use std::path::PathBuf;
use tokio::prelude::*;

fn visit_async(path: PathBuf) -> Box<Future<Item = (), Error = Error> + Send> {
    let task = tokio::fs::read_dir(path)
        .flatten_stream()
        .for_each(move |entry| {
            let path = entry.path();
            if path.is_dir() {
                let task = visit_async(entry.path());
                tokio::spawn(task.map_err(drop));
            } else {
                println!("File: {:?}", path);
            }
            future::ok(())
        })
        .map_err(Error::from);
    Box::new(task)
}

在这里,我会尽量避免使用
tokio::spawn()
,并尝试将其打包成一个单一的未来(通常,我认为您只在不关心结果或执行的情况下才使用tokio::spawn,我们在这里就是这么做的)。这将使等待完成变得容易。我还没有对此进行测试,但沿着这些思路的一些东西可能会起到作用:

let task=tokio::fs::read_dir(路径)
.flatten_stream()
.每个(移动|进入|{
让path=entry.path();
if path.is_dir(){
让task=visit_async(entry.path());
未来::任择::A(任务)
}否则{
println!(“文件:{:?}”,路径);
未来::要么::B(未来::确定(())
}
})
.map_err(错误::from)
.然后| | |{
//完成所有任务后做一些工作
});
框::新建(任务)
这将导致异步任务按顺序执行。您可以对每个使用
和_then
而不是
来并行执行它们,然后
进入_future()。然后_then(| |{…})
插入一些动作以在之后执行

let t = visit_async(PathBuf::from(".")).map_err(drop);
tokio::run(t);

tokio::run(future::ok(()));