如何在 Dart 中的 List.forEach() 中异步/等待 [英] How to Async/await in List.forEach() in Dart
本文介绍了如何在 Dart 中的 List.forEach() 中异步/等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在编写某种机器人(命令行应用程序),但在使用forEach"时遇到异步执行问题.方法.这是我正在尝试做的简化代码:
I'm writing some kind of bot (command line application) and I'm having trouble with async execution when I'm using the "forEach" method. Here is a simplified code of what I'm trying to do :
main() async {
print("main start");
await asyncOne();
print("main end");
}
asyncOne() async {
print("asyncOne start");
[1, 2, 3].forEach(await (num) async {
await asyncTwo(num);
});
print("asyncOne end");
}
asyncTwo(num) async
{
print("asyncTwo #${num}");
}
这是输出:
main start
asyncOne start
asyncOne end
main end
asyncTwo #1
asyncTwo #2
asyncTwo #3
我想要的是:
main start
asyncOne start
asyncTwo #1
asyncTwo #2
asyncTwo #3
asyncOne end
main end
如果有人知道我做错了什么,我将不胜感激.
If someone knows what I'm doing wrong I would appreciate it.
推荐答案
我认为使用 forEach
方法无法实现您想要的效果.但是,它将与 for
循环一起使用.例子;
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");
}
这篇关于如何在 Dart 中的 List.forEach() 中异步/等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文