javascript - ES2015 Promise 链 - 为什么 promisified 函数立即运行?

标签 javascript

为什么下面打印的是 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/

相关文章:

javascript - 使用 Promise.all 时,Node_Redis HGET 解析为 bool 数组

javascript - 如何从 html 输入类型 ="time"获取 Angular Controller 变量中的唯一时间值

javascript - 使用 HTML5 拖放

javascript - Harmony 模块 - 如何处理平台差异?

javascript - 在 FabricJS 中调整多边形、折线、线条的大小而不使用 'scale'

javascript - 使用 JavaScript 中的键从 JSON 中查找值

php - 如何去除tinymce编辑器周围的边框

javascript - 如何使用 jquery 设置 data-url 属性的新值?

javascript - 如何从数组中返回具有指定字母长度的对象?

javascript - Observable.create() 函数的参数是否必须显式定义观察者?