I have a pure JavaScript Promise (built-in implementation or poly-fill):
var promise = new Promise(function (resolve, reject) { /* ... */ });
From the specification, a Promise can be one of:
- 'settled' and 'resolved'
- 'settled' and 'rejected'
- 'pending'
I have a use case where I wish to interrogate the Promise synchronously and determine:
is the Promise settled?
if so, is the Promise resolved?
I know that I can use #then()
to schedule work to be performed asynchronously after the Promise changes state. I am NOT asking how to do this.
This question is specifically about synchronous interrogation of a Promise's state. How can I achieve this?
I've written a little npm package, promise-value, which provides a promise wrapper with a
resolved
flag:https://www.npmjs.com/package/promise-value
It also gives synchronous access to the promise value (or error). This doesn't alter the Promise object itself, following the wrap rather than extend pattern.
what you can do, is to use a variable to store the state, manually set the state to that variable, and check that variable.
of course, this means you must have access to the original code of the promise. If you don't, then you can do:
My solution is more coding, but I think you probably wouldn't have to do this for every promise you use.
You can use an (ugly) hack in Node.js until a native method is offered:
You can make a race with Promise.resolve
It's not synchronous but happens now
A little script for testing and understand their meaning of asynchronously
results with delay(0) (comment the while in delay)
and the results of this test with firefox(chrome keep the order)
promiseState make .race and .then : Level 2
If you're using ES7 experimental you can use async to easily wrap the promise you want to listen.