Is there a way to tell if an ES6 promise is fulfilled/rejected/resolved? [duplicate]

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


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, ...)?



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 MakeQuerablePromise(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;

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.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.