for-loopasynchronousdartasync-awaitfor-await

Dart - Await all async tasks in a for loop


I have a list of Objects in Dart and I want to perform an asynchronous operation with every one of these objects. After all of the asynchronous operations have finished, I want to perform a final operation. I am currently doing this with code that looks like following:

for (int i = 0; i < myObjectList.length; i++) {
  await myAsynchronousOperation(myObjectList[i]);
}
doFinalOperation();

While this technically works, I assume that it is inefficient because the for loop will wait for the first asynchronous operation to finish before starting the second one. So from my understanding we end up synchronously firing asynchronous operations, which can't be the intention of asynchronous programming.

My question therefore is if it is somehow possible to fire all asynchronous operations at once, then wait until they are all finished, and then finally perform the final operation. Thanks in advance!


Solution

  • Use Future.wait to wait for multiple in-flight Futures:

    await Future.wait([
      for (int i = 0; i < myObjectList.length; i++)
        myAsynchronousOperation(myObjectList[i]),
    ]);
    doFinalOperation();