Sequential processing of a variable number of async functions in Dart
Asked Answered
T

1

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?

Thorny answered 25/8, 2017 at 4:40 Comment(0)
G
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.

Guillemot answered 25/8, 2017 at 5:28 Comment(2)
So simple... Why didn't I think of it? I managed to solve it through recursion, but your solution is much more elegant.Thorny
You can also use Future.forEach(argList, expensiveFunction).Radiomicrometer

© 2022 - 2024 — McMap. All rights reserved.