Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
391 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...