3

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?

I have tried this:

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

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?

Igor F.
  • 2,649
  • 2
  • 31
  • 39

1 Answers1

6

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

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

There are some nice examples on the language tour.

matanlurey
  • 8,096
  • 3
  • 38
  • 46
  • So simple... Why didn't I think of it? I managed to solve it through recursion, but your solution is much more elegant. – Igor F. Aug 25 '17 at 06:14
  • 2
    You can also use `Future.forEach(argList, expensiveFunction)`. – lrn Aug 25 '17 at 10:16