我需要在 Dart 中重复调用一个异步函数,我们称之为expensiveFunction,以获取可变数量的参数。但是,由于每个调用都非常消耗内存,因此我无法并行运行它们。我如何强制它们按顺序运行?
我已经尝试过这个:
argList.forEach( await (int arg) async {
Completer c = new Completer();
expensiveFunction(arg).then( (result) {
// do something with the result
c.complete();
});
return c.future;
});
Run Code Online (Sandbox Code Playgroud)
但并没有达到预期的效果。仍在为每个inexpensiveFunction并行调用。我实际上需要的是在循环中等待,直到完成,然后才继续处理 中的下一个元素。我怎样才能做到这一点?argargListforEachexpensiveFunctionargList
您需要for在此处使用经典循环:
doThings() async {
for (var arg in argList) {
await expensiveFunction(arg).then((result) => ...);
}
}
Run Code Online (Sandbox Code Playgroud)
语言之旅中有一些很好的例子。
| 归档时间: |
|
| 查看次数: |
796 次 |
| 最近记录: |