javascript - 关于事件循环:promise 如何与同步脚本一起工作
问题描述
通常,我们认为 promise 创建一个微任务,并将其添加到微任务队列中。一旦调用堆栈为空,微任务将被压入调用堆栈。
但让我感到困惑的是这个例子:
console.log(1)
Promise.resolve().then((res) => {
console.log(2)
})
console.log(3);
在我看来,我认为它是这样工作的:
console.log(1) //push into call stack
// console log: 1 (pop from call stack)
//so now call stack is empty
Promise.resolve().then((res) => { //here we create a microtask into microtask queue,
//and stack is empty,
//but it not push into call stack, why???
console.log(2) //no console now
})
console.log(3); //console log: 3
//console.log: 2
所以我一定是错的,但是哪一步是我错的,确切的规则是什么。
解决方案
感谢@Jaromanda X 和@MinusFour。我发现我的错误在哪里:
//this block will push into call stack
//------- a block --------
console.log(1) //console log: 1
//so here the block is still in stack.
Promise.resolve().then((res) => { //create a microtask
console.log(2)
})
console.log(3); //console log: 3
//------------------------
//here the block is pop from call stack.
//so call stack is empty now
//so microtask push into call stack
//console log: 2
最重要的是javascript块是基本stack frame
的call stack
,而不是单一的语句。
推荐阅读
- javascript - Flask-SocketIO 简单的通信器在 Chrome 和 Firefox 上运行良好,但在 IE 上不行
- python - 如何在python中获取属性的源代码
- html - 即使指向的网站来自我自己的网站,我是否需要将 rel="noopener" 放到每个 target="blank" 中?
- python - 调用matplolib pyplot waitforbuttonpress()时获取键值
- entity-framework - 如何在一个 Razor 页面中访问 2 个 DBContext
- c# - 如何将类型“System.Collections.Generic.List”隐式转换为“System.Collections.Generic.List”?
- python-3.x - 在 Python 中仅导入 docx 的特定部分
- angular - Angular 7拖放交换元素
- java - 当任何新项目添加到回收站视图中时如何自动发布数据
- tsql - 使用文件名变量日期脚本恢复数据库