How to call an async API fully synchronously within a loop in Dart?
For example, if I have
for(...) {
await doSomethingLongAsync();
}
as I understand, doSomethingLongAsync() will be invoked sequentionally but asynchronously on each iteration of the loop, i.e. each subsequent iteration of the loop will asynchronously call doSomethingLongAsync() even before the call of the previous iteration completes.
What I need is to make sure that a subsequent iteration of the loop does not invoke doSomethingLongAsync() until the previous iteration's invokation of the same function fully completes.
CodePudding user response:
as I understand, doSomethingLongAsync() will be invoked sequentionally but asynchronously on each iteration of the loop, i.e. each subsequent iteration of the loop will asynchronously call doSomethingLongAsync() even before the call of the previous iteration completes.
That is not correct, when you await, it will not move on (within the context of the async function) until the Future being awaited completes.
What I need is to make sure that a subsequent iteration of the loop does not invoke doSomethingLongAsync() until the previous iteration's invokation of the same function fully completes.
The code you have written already does this.
To illustrate, try running this code:
Future<void> main() async {
for (int i = 0; i < 10; i ) {
print('start loop $i');
await doSomethingLongAsync(i);
print('end loop $i\n');
}
}
Future<void> doSomethingLongAsync(int i) async {
print('start doSomethingLongAsync $i');
await Future.delayed(const Duration(seconds: 2));
print('end doSomethingLongAsync $i');
}
You will see that it does not continue to the next iteration of the loop until the Future being awaited is complete.
