Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Check whether a promise is finished / resolved / rejected
function delay(msec, value) {
return new Promise(done => window.setTimeout((() => done(value)), msec));
}
function isResolved(promise) {
  return Promise.race([delay(0, false), promise.then(() => true, () => false)]);
}
function isRejected(promise) {
  return Promise.race([delay(0, false), promise.then(() => false, () => true)]);
}
function isFinished(promise) {
  return Promise.race([delay(0, false), promise.then(() => true, () => true)]);
}
isFinished(Promise.resolve(42)).then(result => console.log(result ? "Resolved" : "Not resolved"));
// => "Resolved"
isFinished(delay(100)).then(result => console.log(result ? "Resolved" : "Not resolved"));
// => "Not resolved"
isFinished(delay(1)).then(result => console.log(result ? "Resolved" : "Not resolved"));
// => "Resolved"
// oh...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment