Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens if i reject / resolve multiple times in Kriskowal's q?

I'm studying the promises pattern and using kriskowal's q for node.js,

having this snippet:

var deferred = Q.defer(); try {     messageData = JSON.parse(message); } catch (e) {     global.logger.warn('Error parsing JSON message.');     deferred.reject(e); } ... if (some_reason)     deferred.resolve(something); ... return deferred.promise; 

What if both the parser fails and some_reason is true?

Will the execution procede from rejecting through resolving and both promise's method be called at different times, thus generating a bug?

Should i avoid to call reject/resolve multiple times?

like image 908
Luca Vitucci Avatar asked Aug 13 '13 19:08

Luca Vitucci


People also ask

Can you reject a Promise multiple times?

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 many times can a Promise be rejected?

A Promise executor should call only one resolve or one reject . Once one state is changed (pending => fulfilled or pending => rejected), that's all. Any further calls to resolve or reject will be ignored.

What happens if you dont resolve Promise?

A promise is just an object with properties in Javascript. There's no magic to it. So failing to resolve or reject a promise just fails to ever change the state from "pending" to anything else. This doesn't cause any fundamental problem in Javascript because a promise is just a regular Javascript object.

What is resolve reject?

resolve(value) — if the job is finished successfully, with result value . reject(error) — if an error has occurred, error is the error object.


1 Answers

Since promises can only resolve once (to either fulfilled or rejected), the first resolution wins and any further calls will be ignored. From the docs:

In all cases where a promise is resolved (i.e. either fulfilled or rejected), the resolution is permanent and cannot be reset. Attempting to call resolve, reject, or notify if promise is already resolved will be a no-op.

Should i avoid to call reject/resolve multiple times?

You can even design your application letting two methods "race" against each other to resolve a deferred, but in general it should be avoided to reduce confusion of a reader.

like image 113
Bergi Avatar answered Sep 18 '22 14:09

Bergi