有没有办法判断 ES6 承诺是否已履行/拒绝/解决? [英] Is there a way to tell if an ES6 promise is fulfilled/rejected/resolved?

查看:13
本文介绍了有没有办法判断 ES6 承诺是否已履行/拒绝/解决?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我习惯于使用 Dojo Promise,我可以在其中执行以下操作:

I'm used to Dojo promises, where I can just do the following:

promise.isFulfilled();
promise.isResolved();
promise.isRejected();

有没有办法确定 ES6 承诺是否已履行、已解决或被拒绝?如果没有,有没有办法使用 Object.defineProperty(Promise.prototype, ...) 来填充该功能?

Is there a way to determine if an ES6 promise is fulfilled, resolved, or rejected? If not, is there a way to fill in that functionality using Object.defineProperty(Promise.prototype, ...)?

推荐答案

它们不是规范的一部分,也没有访问它们的标准方法,您可以使用它来获取构建 polyfill 的承诺的内部状态.但是,您可以通过创建包装器将任何标准承诺转换为具有这些值的承诺,

They are not part of the specification nor is there a standard way of accessing them that you could use to get the internal state of the promise to construct a polyfill. However, you can convert any standard promise into one that has these values by creating a wrapper,

function MakeQueryablePromise(promise) {
    // Don't create a wrapper for promises that can already be queried.
    if (promise.isResolved) return promise;
    
    var isResolved = false;
    var isRejected = false;

    // Observe the promise, saving the fulfillment in a closure scope.
    var result = promise.then(
       function(v) { isResolved = true; return v; }, 
       function(e) { isRejected = true; throw e; });
    result.isFulfilled = function() { return isResolved || isRejected; };
    result.isResolved = function() { return isResolved; }
    result.isRejected = function() { return isRejected; }
    return result;
}

这不会像修改原型那样影响所有 Promise,但它确实允许您将 Promise 转换为公开其状态的 Promise.

This doesn't affect all promises, as modifying the prototype would, but it does allow you to convert a promise into a promise that exposes it state.

这篇关于有没有办法判断 ES6 承诺是否已履行/拒绝/解决?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆