关于事件循环:Promise如何与同步脚本一起使用

时间:2018-08-24 03:15:50

标签: javascript promise event-loop

很常见,我们认为promise会创建一个微任务,并将其添加到microtast队列中。一旦调用堆栈为空,微任务将被推入调用堆栈。

但是让我感到困惑的是这个例子:

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

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

1 个答案:

答案 0 :(得分:0)

感谢@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 block stack frame中的基本call stack,而不是单个语句。