crazy4groovy
8/10/2017 - 3:53 PM

(Async) detect the state of a Promise, pass in callbacks for each state.

(Async) detect the state of a Promise, pass in callbacks for each state.

Promise.prototype.state = function promiseState(isPending, isResolved, isRejected) {
  Promise.race([this, Promise.resolve('!a value that p should not return!')]).then(function(value) {
    if (value === '!a value that p should not return!') {
      (typeof(isPending) === 'function') && isPending();
    } else {
      (typeof(isResolved) === 'function') && isResolved(value);
    }
  }, function(reason) {
    (typeof(isRejected) === 'function') && isRejected(reason);
  });
}

//https://stackoverflow.com/a/31758728/356990