首页 > 解决方案 > 关于事件循环: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

所以我一定是错的,但是哪一步是我错的,确切的规则是什么。

标签: javascriptpromiseevent-loop

解决方案


感谢@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 framecall stack而不是单一的语句


推荐阅读