在Dart中顺序处理可变数量的异步函数 [英] Sequential processing of a variable number of async functions in Dart

查看:129
本文介绍了在Dart中顺序处理可变数量的异步函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在Dart中反复调用异步函数,我们将其命名为 expensiveFunction ,以获取可变数量的参数。但是,由于每个调用都占用大量内存,因此我无法并行运行它们。我如何强制它们按顺序运行?

I need to repeatedly call an asynchronous function in Dart, let's call it expensiveFunction, for a variable number of arguments. However, since each call is quite memory consuming, I cannot afford to run them in parallel. How do I force them to run in sequence?

我已经尝试过:

argList.forEach( await (int arg) async {
  Completer c = new Completer();
  expensiveFunction(arg).then( (result) {
    // do something with the result
    c.complete();
  });
  return c.future;
});

,但没有达到预期的效果。 expensiveFunction 仍在为 argList arg 并行调用c>。我真正需要的是在 forEach 循环中等待,直到 expensiveFunction 完成,然后再继续下一个元素在 argList 中。我该如何实现?

but it hasn't had the intended effect. The expensiveFunction is still being called in parallel for each arg in argList. What I actually need is to wait in the forEach loop until the expensiveFunction completes and only then to proceed with the next element in the argList. How can I achieve that?

推荐答案

您将要使用经典的 在这里循环:

You'll want to use a classic for loop here:

doThings() async {
  for (var arg in argList) {
    await expensiveFunction(arg).then((result) => ...);
  }
}

有一些很好的例子语言之旅

这篇关于在Dart中顺序处理可变数量的异步函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆