Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

q.js : Is it possible to know if a promise has resolved/rejected or not

Tags:

promise

q

In my scenario I return a promise when I'm making a request.

In the end I resolve/reject the deferred obj.

I want to reuse the promise if it hasn't been resolved/rejected.

Any info would be useful.

like image 287
phani Avatar asked Nov 20 '14 12:11

phani


People also ask

How do I know if a Javascript 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; }); // ...

Can a Promise resolve and reject?

A Promise that is resolved with the given value, or the promise passed as value, if the value was a promise object. It may be either fulfilled or rejected — for example, resolving a rejected promise will still result in a rejected promise.

What happens when a Promise is rejected Javascript?

catch " around the executor automatically catches the error and turns it into rejected promise. This happens not only in the executor function, but in its handlers as well. If we throw inside a . then handler, that means a rejected promise, so the control jumps to the nearest error handler.

Can a JS Promise be rejected more than once?

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.


2 Answers

I got the answer by looking into q.js source.

deferred.promise.inspect().state

This will return the state of the promise.

returns "fulfilled" if it was resolved or fulfilled
returns "rejected" if it was rejected
returns "pending" if it hasn't been resolved or rejected
like image 71
phani Avatar answered Oct 22 '22 04:10

phani


You can use the state inspection methods which are less verbose. And calling a method is always better than checking === with state. If there is a typo with a method you will get an error immediately. With === a typo will return false which could be a bug. From the Q API reference,

promise.isFulfilled()

Returns whether a given promise is in the fulfilled state. When the static version is used on non-promises, the result is always true.

promise.isRejected()

Returns whether a given promise is in the rejected state. When the static version is used on non-promises, the result is always false.

promise.isPending()

Returns whether a given promise is in the pending state. When the static version is used on non-promises, the result is always false.

like image 36
Jordan Nelson Avatar answered Oct 22 '22 04:10

Jordan Nelson