import 'dart:async';
void main() async {
Future.microtask(() => print(1));
Future.value(2).then(print);
Future.sync(() => print(3));
Future.sync(() => 4).then(print);
}
我在 dartpad 中观察到的输出:
3
1
2
4
为什么微任务没有先执行?两个Future.sync函数以不同的顺序打印它们有什么不同。
最佳答案
.then()
方法的一个重要方面是您可以在文档中找到以下内容:
When this future completes with a
value
, the onValue callback will be called with that value. If this future is already completed, the callback will not be called immediately, but will be scheduled in a later microtask.
https://api.dart.dev/stable/2.15.1/dart-async/Future/then.html
所以发生的事情是:
- 您安排一个微任务来调用
print(1)
。 Future.value(2)
同步完成,下面的.then
将在微任务中完成。微任务队列现在为:print(1)
、print(2)
。- 第三行是同步的,并且立即完整运行,因此我们运行
print(3)
。这给出了输入中的第一行。 - 由于
.then()
,我们安排了一个新的微任务。微任务队列现在为:print(1)
、print(2)
、print(4)
。
完成 main()
后,我们按微任务出现的顺序运行微任务,这解释了其余的输出。
一个重要的注意事项是,您永远不会等待 .then()
方法返回的任何 Future
,因此任何异步内容将在 时首先执行>main()
已完成。
关于dart - 请在这里解释一下 Dart 中 Futures 的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70844891/