q.js : Is it possible to know if a promise has res

2019-06-15 09:42发布

问题:

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.

回答1:

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


回答2:

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.



标签: promise q