为什么下面打印的是 2 1 3
而不是我预期的 1 2 3
?
(function() {
return new Promise(function(resolve) {
document.write('2');
resolve();
})
.then(log('1')); // I was expecting this `log` function invocation to run first
}());
function log(message) {
document.write(message);
return function() {
document.write('3');
}
}
我使用的是 Chrome 49.0.2623.112 m。
最佳答案
来自 MDN :
The executor function is executed immediately by the Promise implementation which provides the resolve and reject functions (the executor is called before the Promise constructor even returns the created object).
您的初始匿名函数运行,并且在其中运行 new Promise()
调用,首先要做的是运行您的执行函数(对构造函数的回调)。 那 又会立即调用 document.write(2)
,因此您首先看到的是 2
。
编辑 — 看到您问题中的说明,它归结为简单的 JavaScript 调用顺序。您的 Promise 构造函数仅包含 return
语句,其形式为:
return new C(fn).then(expr);
JavaScript 在开始处理表达式的其余部分之前完成 new C(fn)
调用。一旦 new
返回(此时 2
已经被打印),表达式的 .then(expr)
部分被评估.这将通过 .then()
的参数列表中的 log()
调用触发 1
的打印。
必须首先对 .
运算符的左侧进行完整求值,否则就没有地方可以查找“then”属性。
关于javascript - ES2015 Promise 链 - 为什么 promisified 函数立即运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37050489/