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?
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.
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.
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.
resolve(value) — if the job is finished successfully, with result value . reject(error) — if an error has occurred, error is the error object.
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.
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