I'm studying the promises pattern and using kriskowal's q for node.js,
我正在研究promises模式并使用kriskowal的q作为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?
如果解析器失败且some_reason为真,该怎么办?
Will the execution procede from rejecting through resolving and both promise's method be called at different times, thus generating a bug?
执行会从拒绝通过解析进行,并且会在不同的时间调用promise的方法,从而产生错误吗?
Should i avoid to call reject/resolve multiple times?
我应该避免多次致电拒绝/解决?
1 个解决方案
#1
40
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:
由于promises只能解析一次(要么已完成或被拒绝),第一个分辨率将获胜,任何进一步的调用都将被忽略。来自文档:
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.
您甚至可以设计您的应用程序,让两种方法相互“竞争”以解决延迟,但一般来说应该避免减少读者的混淆。
#1
40
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:
由于promises只能解析一次(要么已完成或被拒绝),第一个分辨率将获胜,任何进一步的调用都将被忽略。来自文档:
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.
您甚至可以设计您的应用程序,让两种方法相互“竞争”以解决延迟,但一般来说应该避免减少读者的混淆。