【问题标题】:How ES2015 Promise actually works when resolving another thenable?解决另一个 thenable 时,ES2015 Promise 是如何工作的?
【发布时间】:2016-01-21 17:22:34
【问题描述】:

我在尝试 ES2015 Promises 时遇到了奇怪的问题:

var webdriver = require('webdriverio');

(new Promise(function (resolve, reject) {
  var client = webdriver.remote({desiredCapabilities: {browserName: 'chrome'}}).init();
  client.then(function () {
    console.log(typeof client.end); // outputs "function"
    resolve(client)
  }).catch(function (e) {
    reject(e);
  });
})).then(function (client) {
  console.log(typeof client.end); // outputs "undefined"
}).catch(function (e) {
  console.log(e);
});

在上面的代码中,当我解析client 时,会发生某种魔术。在调用 resolve 之前,客户端包含 state=fulfilledvalue 属性,以及 then、end、click、waitForExist 等方法。但在回调中,我只收到原始客户端对象的 value 属性作为参数。我的问题很简单,ES2015 Promise 在解析此类对象时执行了什么样的巫术?

与这种奇怪的行为相反,调用 resolve({client}) 按预期工作 - then((result) => result.client.end())

【问题讨论】:

标签: javascript es6-promise webdriver-io


【解决方案1】:

这是 Promise 链中的标准行为,这意味着 ES2015 Promise 库识别您正在使用另一个 Promise 解决一个 Promise 并等待该 Promise 解决,然后继续链,这就是为什么在回调中,您获取实际值,而不是您之前解决的 promise 对象。

然而,在第二种情况下,您将 Promise 包装在一个对象中,这会阻止 Promise 库将其识别为 Promise,因此它只是将其传递给下一个回调。

【讨论】:

    猜你喜欢
    • 2018-07-16
    • 2023-03-31
    • 1970-01-01
    • 2019-08-03
    • 2016-01-20
    • 1970-01-01
    • 2015-03-17
    • 2018-01-24
    • 2021-07-24
    相关资源
    最近更新 更多