19.Future&Microtask
多个 Future
下面多个 Future 的执行顺序会是什么样的呢?
void main() {
Future( () {
sleep(const Duration(seconds: 1));
return "${DateTime.now()}: 1";
})
.then((value){
print(value);
});
Future( () {
sleep(const Duration(seconds: 1));
return "${DateTime.now()}: 2";
})
.then((value){
print(value);
});
Future( () {
sleep(const Duration(seconds: 1));
return "${DateTime.now()}: 3";
})
.then((value){
print(value);
});
Future( () {
sleep(const Duration(seconds: 1));
return "${DateTime.now()}: 4";
})
.then((value){
print(value);
});
}分析: 多个 Future 是按照代码顺序,依次添加到任务队列的,会依次被执行。所以会按顺序输出。
依赖连续调用
如果有几个异步任务是有一定的顺序或者结果依赖的,那么可以通过 then 的链式调用进行:
输出的结果:
多个无依赖的任务结束后处理
开发中,我们还会遇到一些多个异步任务都执行完再去做一些事情的场景。 Future 也有提供这种歌场景的功能:
输出:
这里和使用单个 Future 一样,也可以通过 then 来处理结果。通过输出内容我们可以发现,这里的 then 里的 value 其实是一个数组,并且如果数组内部的顺序是和 Future 数组的顺序保持一致的。
scheduleMicrotask
scheduleMicrotask 也是异步编程常用的一个 API,它的优先级比 Future 会高,同一队列中,会优先将 微任务 处理完成再去处理 Future。
题目
这里通过一个题目考验一下:
思考一下这里的输出会是什么样的顺序呢?不要运行,欢迎在评论中告诉我哦。
Last updated
Was this helpful?