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?