关于promise疑惑
发布于 12 天前 作者 nqdy666 401 次浏览 来自 问答
var Promise = require('promise')
var promise = new Promise(function (resolve) {
  resolve()
})
promise.then(function () {
  console.log(2)
})

var i = 0
while ( i < 1000000000 ) {
  i++
}
console.log(1)

以上代码,为什么测试的时候一直输出的1 2,而不会输出2 1呢?

11 回复

then 里面的是异步执行的
Promises/A+

2.2.4 onFulfilled or onRejected must not be called until the execution context stack contains only platform code. [3.1].

3.1 Here “platform code” means engine, environment, and promise implementation code. In practice, this requirement ensures that onFulfilled and onRejected execute asynchronously, after the event loop turn in which then is called, and with a fresh stack. This can be implemented with either a “macro-task” mechanism such as setTimeout or setImmediate, or with a “micro-task” mechanism such as MutationObserver or process.nextTick. Since the promise implementation is considered platform code, it may itself contain a task-scheduling queue or “trampoline” in which the handlers are called.

next tick 后执行的,也就是在运行完 while 后。

@William17 我已经用while延迟很久了,异步的话,也应该先输出2,再输出1把

@yjhjstz 能解释一下next tick,或者有什么文章推荐一下

@nqdy666 你对异步的理解不太正确, 正如规范里说的

onFulfilled and onRejected execute asynchronously, after the event loop turn in which then is called, and with a fresh stack.

then里的, 会在下一个事件循环才被执行, 而你的while, console.log(1)是在当前的事件循环

@nqdy666 简单来说 while不是延迟,而是一种阻塞,把cpu都占了,在while执行完成前,其它异步代码都是被阻塞住了,没法执行。

@zhou-yg @William17 @yjhjstz 嗯嗯,稍微明白了,谢谢你们

前面的都说得对,异步的语句都是放进队列,非异步的语句才放进栈,代码只有在栈里才是被“执行”的。

所有同步代码执行完毕,才会执行队列中的异步代码吧

一个简单的方法, 你只要想着你的代码中同步的代码运行完了才会运行异步就好了

回到顶部