Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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

like image 884
knpwrs Avatar asked Jan 31 '14 16:01

knpwrs


People also ask

How do I know if JavaScript Promise is fulfilled?

The best place to know if a promise is resolved is in . then(). Testing if a Promise is fullfilled would create a polling loop which is most likely the wrong direction. async/await is a nice construct if you'd like to reason async code synchronously.

How do you know when a Promise is resolved?

If the value is a promise then promise is returned. If the value has a “then” attached to the promise, then the returned promise will follow that “then” to till the final state. The promise fulfilled with its value will be returned.

How does JavaScript figure out that a Promise is resolved?

Resolving a promise We check if the result is a promise or not. If it's a function, then call that function with value using doResolve() . If the result is a promise then it will be pushed to the deferreds array. You can find this logic in the finale function.

Does Promise return After resolve?

The Promise. resolve() method "resolves" a given value to a Promise . If the value is a promise, that promise is returned; if the value is a thenable, Promise. resolve() will call the then() method with two callbacks it prepared; otherwise the returned promise will be fulfilled with the value.


1 Answers

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.

like image 138
chuckj Avatar answered Sep 19 '22 18:09

chuckj