我有一个对象向量,其中包含一个 resolve()
方法,该方法使用 reqwest
查询外部 Web API。在对每个对象调用 resolve()
方法后,我想打印出每个请求的结果。
这是我的半异步代码,它可以编译和工作(但实际上并不是完全异步):
for mut item in items {
item.resolve().await;
item.print_result();
}
我尝试使用tokio::join!
来生成所有异步调用并等待它们完成,但我可能做错了什么:
tokio::join!(items.iter_mut().for_each(|item| item.resolve()));
这是我遇到的错误:
error[E0308]: mismatched types
--> src\main.rs:25:51
|
25 | tokio::join!(items.iter_mut().for_each(|item| item.resolve()));
| ^^^^^^^^^^^^^^ expected `()`, found opaque type
|
::: src\redirect_definition.rs:32:37
|
32 | pub async fn resolve(&mut self) {
| - the `Output` of this `async fn`'s found opaque type
|
= note: expected unit type `()`
found opaque type `impl std::future::Future`
如何同时调用所有实例的resolve()
方法?
这段代码反映了答案-现在我正在处理一些我不太理解的借用检查器错误-我应该使用'static
注释我的某些变量吗?
let mut items = get_from_csv(path);
let tasks: Vec<_> = items
.iter_mut()
.map(|item| tokio::spawn(item.resolve()))
.collect();
for task in tasks {
task.await;
}
for item in items {
item.print_result();
}
error[E0597]: `items` does not live long enough
--> src\main.rs:18:25
|
18 | let tasks: Vec<_> = items
| -^^^^
| |
| _________________________borrowed value does not live long enough
| |
19 | | .iter_mut()
| |___________________- argument requires that `items` is borrowed for `'static`
...
31 | }
| - `items` dropped here while still borrowed
error[E0505]: cannot move out of `items` because it is borrowed
--> src\main.rs:27:17
|
18 | let tasks: Vec<_> = items
| -----
| |
| _________________________borrow of `items` occurs here
| |
19 | | .iter_mut()
| |___________________- argument requires that `items` is borrowed for `'static`
...
27 | for item in items {
| ^^^^^ move out of `items` occurs here
for_each
旨在原地执行,不返回任何内容。您想要的是将每个项目映射到调用resolve
以产生Future
,然后将它们收集到向量中。从那里开始,您需要等待所有任务完成。 - Alexey Larionovjoin
可以实现并发,但不一定是并行的。可能会在这里找到一些解决方法。 - Alexey Larionov