Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
106
rated 0 times [  107] [ 1]  / answers: 1 / hits: 32135  / 11 Years ago, fri, january 31, 2014, 12:00:00

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



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


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


More From » promise

 Answers
8

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;
}

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.


[#72812] Thursday, January 30, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
damiondenzelc

Total Points: 268
Total Questions: 116
Total Answers: 116

Location: North Korea
Member since Tue, Jun 16, 2020
4 Years ago
damiondenzelc questions
Tue, Nov 24, 20, 00:00, 4 Years ago
Thu, Oct 1, 20, 00:00, 4 Years ago
Wed, Apr 15, 20, 00:00, 4 Years ago
;