js promisestatus

Solutions on MaxInterview for js promisestatus by the best coders in the world

showing results for - "js promisestatus"
Camille
04 Jun 2017
1/**
2 * This function allow you to modify a JS Promise by adding some status properties.
3 * Based on: http://stackoverflow.com/questions/21485545/is-there-a-way-to-tell-if-an-es6-promise-is-fulfilled-rejected-resolved
4 * But modified according to the specs of promises : https://promisesaplus.com/
5 */
6function MakeQuerablePromise(promise) {
7    // Don't modify any promise that has been already modified.
8    if (promise.isResolved) return promise;
9
10    // Set initial state
11    var isPending = true;
12    var isRejected = false;
13    var isFulfilled = false;
14
15    // Observe the promise, saving the fulfillment in a closure scope.
16    var result = promise.then(
17        function(v) {
18            isFulfilled = true;
19            isPending = false;
20            return v; 
21        }, 
22        function(e) {
23            isRejected = true;
24            isPending = false;
25            throw e; 
26        }
27    );
28
29    result.isFulfilled = function() { return isFulfilled; };
30    result.isPending = function() { return isPending; };
31    result.isRejected = function() { return isRejected; };
32    return result;
33}