How to wait for forEach to complete with asynchronous callbacks?

6,051

Solution 1

Iterable.forEach, Map.forEach, and Stream.forEach are meant to execute some code on each element of a collection for side effects. They take callbacks that have a void return type. Consequently, those .forEach methods cannot use any values returned by the callbacks, including returned Futures. If you supply a function that returns a Future, that Future will be lost, and you will not be able to be notified when it completes. You therefore cannot wait for each iteration to complete, nor can you wait for all iterations to complete.

Do NOT use .forEach with asynchronous callbacks.

Instead, if you want to wait for each asynchronous callback sequentially, just use a normal for loop:

for (var mapEntry in gg.entries) {
  await Future.delayed(const Duration(seconds: 5));
}

(In general, I recommend using normal for loops over .forEach in all but special circumstances. Effective Dart has a mostly similar recommendation.)

If you really prefer using .forEach syntax and want to wait for each Future in succession, you could use Future.forEach (which does expect callbacks that return Futures):

await Future.forEach(
  gg.entries,
  (entry) => Future.delayed(const Duration(seconds: 5)),
);

If you want to allow your asynchronous callbacks to possibly run in parallel, you can use Future.wait:

await Future.wait([
  for (var mapEntry in gg.entries)
    Future.delayed(const Duration(seconds: 5)),
]);

See https://github.com/dart-lang/linter/issues/891 for a request for an analyzer warning if attempting to use an asynchronous function as a Map.forEach or Iterable.forEach callback (and for a list of many similar StackOverflow questions).

Solution 2

You can do it like this way using of Future.forEach

main() async {
  print("main start");
  await asyncOne();
  print("main end");
}

asyncOne() async {
  print("asyncOne start");
  await Future.forEach([1, 2, 3], (num) async {
    await asyncTwo(num);
  });
  print("asyncOne end");
}

asyncTwo(num) async
{
  print("asyncTwo #${num}");
}
Share:
6,051
Jeet Agrawal
Author by

Jeet Agrawal

Updated on December 23, 2022

Comments

  • Jeet Agrawal
    Jeet Agrawal over 1 year

    sample code

    Map<String,String> gg={'gg':'abc','kk':'kojk'};
    
    Future<void> secondAsync() async {
      await Future.delayed(const Duration(seconds: 2));
      print("Second!");
      gg.forEach((key,value) async{await Future.delayed(const Duration(seconds: 5));
      print("Third!");
    });
    }
    
    Future<void> thirdAsync() async {
      await Future<String>.delayed(const Duration(seconds: 2));
      print('third');
    }
    
    void main() async {
      secondAsync().then((_){thirdAsync();});
    }
    

    output

    Second!
    third
    Third!
    Third!
    

    as you can see i want to use to wait until foreach loop of map complete to complete then i want to print third
    expected Output

    Second!
    Third!
    Third!
    third