Async/await in List.forEach()
You need to use 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}");
}
I don't think it's possible to achieve what you want with the forEach
method. However it will work with a for
loop. Example;
asyncOne() async {
print("asyncOne start");
for (num number in [1, 2, 3])
await asyncTwo(number);
print("asyncOne end");
}
I know this is an old question, but I'll leave here a new answer, hoping this help someone in the future.
You can use forEach for what you're trying to achieve by doing something like this:
asyncOne() async {
print("asyncOne start");
await Future.forEach([1, 2, 3],(num) async {
await asyncTwo(num);
});
print("asyncOne end");
}