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, ...)
?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With