如果我多次拒绝/解决Kriskowal q中的问题,会发生什么? [英] What happens if i reject / resolve multiple times in Kriskowal's q?

查看:63
本文介绍了如果我多次拒绝/解决Kriskowal q中的问题,会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究Promise模式,并将kriskowal的q用于node.js,

I'm studying the promises pattern and using kriskowal's q for node.js,

具有以下代码段:

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;

如果解析器都失败并且 some_reason 为真该怎么办?

What if both the parser fails and some_reason is true?

执行是否会从拒绝通过解析开始,并且两个promise的方法在不同的时间被调用,从而产生错误?

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?

推荐答案

由于承诺只能解决一次(对于任一实现被拒绝),则第一个解决方案将获胜,任何其他调用均将被忽略.来自文档:

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.

这篇关于如果我多次拒绝/解决Kriskowal q中的问题,会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆