Suppose some code does
// promise.js let p = new Promise(() => { /* ... */ }) export default p
where Promise
is an ES6 Promise. Suppose some other code has a reference only to p
. How can that code tell if p
is resolved or not?
// other.js import p from './promise.js' // console.log('p is resolved?', ______)
Is there something we can fill in the blank with that would show true or false depending on whether the promise is resolved or not?
You need to do something like this: import p from './promise. js' var isResolved = false; p. then(function() { isResolved = true; }); // ...
No. It is not safe to resolve/reject promise multiple times. It is basically a bug, that is hard to catch, becasue it can be not always reproducible.
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.
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.
Quoting the MDN documentation:
By design, the instant state and value of a promise cannot be inspected synchronously from code, without calling the then() method.
So, you need to call the .then
method.
The ES6 Promise constructor does not have a property that can tell you the state of the promise. You need to do something like this:
import p from './promise.js' var isResolved = false; p.then(function() { isResolved = true; }); // ... At some point in the future. console.log('p is resolved?', isResolved);
There is an internal property called PromiseState
but you can't access it. Here is the spec.
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