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

情到浓时终转凉″ 提交于 2019-11-26 11:28:34

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/18217640/what-happens-if-i-reject-resolve-multiple-times-in-kriskowals-q

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!