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呢?
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.
@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)
是在当前的事件循环