Skip to content
Advertisement

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?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement