Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell if a promise is resolved? [duplicate]

Tags:

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?

like image 309
trusktr Avatar asked Mar 01 '16 06:03

trusktr


People also ask

How do you check if a Promise has been resolved?

You need to do something like this: import p from './promise. js' var isResolved = false; p. then(function() { isResolved = true; }); // ...

What happens if you resolve a Promise twice?

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.

How does Javascript figure out that a Promise is resolved?

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.

What does resolve () do in a Promise?

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.


2 Answers

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.

like image 165
ashish Avatar answered Sep 29 '22 23:09

ashish


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.

like image 40
nstoitsev Avatar answered Sep 29 '22 23:09

nstoitsev