跳到主要内容
CNode

关于promise疑惑

问答
Nnqdy666发布于 10 年前最后回复 10 年前
1158550
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)

N
Neil-UWA#1110 年前

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

Z
zhengjun87#910 年前

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

F
flamingtop#810 年前

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

Z
zhou-yg#610 年前
引用 nqdy666@William17 我已经用while延迟很久了,异步的话,也应该先输出2,再输出1把

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

W
William17#510 年前
引用 nqdy666@William17 我已经用while延迟很久了,异步的话,也应该先输出2,再输出1把

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

N
nqdy666#410 年前
引用 yjhjstznext tick 后执行的,也就是在运行完 while 后。

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

N
nqdy666#310 年前
引用 William17then 里面的是异步执行的 Promises/A+ 2.2.4 onFulfilled or onRejected must not be called until the executio...

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

Y
yjhjstz#210 年前

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

W
William17#110 年前

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.

参与回复

登录后即可参与回复。登录