dart - 请在这里解释一下 Dart 中 Futures 的行为

标签 dart

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

所以发生的事情是:

  1. 您安排一个微任务来调用 print(1)
  2. Future.value(2) 同步完成,下面的 .then 将在微任务中完成。微任务队列现在为:print(1)print(2)
  3. 第三行是同步的,并且立即完整运行,因此我们运行 print(3)。这给出了输入中的第一行。
  4. 由于.then(),我们安排了一个新的微任务。微任务队列现在为:print(1)print(2)print(4)

完成 main() 后,我们按微任务出现的顺序运行微任务,这解释了其余的输出。

一个重要的注意事项是,您永远不会等待 .then() 方法返回的任何 Future,因此任何异步内容将在 时首先执行>main() 已完成。

关于dart - 请在这里解释一下 Dart 中 Futures 的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70844891/

相关文章:

dart - 如何加载资源文件或包 : URIs in Dart?

xml - 如何在Flutter中对来自HttpClient流的XML元素进行分组

sqlite - 如何在 ChangeNotifier 中使用 Futures?

android - Flutter:Map <String,T>的ListView.Builder类型

javascript - 如何在 Dart 中使用 Facebook SDK?

dart - Google Dart 有类似 regex.exec() 的东西吗?

xml - 无法将最后一个 xml 版本添加到 flutter 项目

multithreading - 如何处理 Isolates 中抛出的异常?

dart - 如何对 "List": map, 组执行这些操作、查找、聚合、排序?

firebase - 如何从Firebase Flutter获取fieldValue.arrayUnion数据