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

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

问题描述

我正在研究 promises 模式并在 node.js 中使用 kriskowal 的 q,

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?

执行会不会从rejecting到resolve,两个promise的方法会在不同的时间被调用,从而产生bug?

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?

推荐答案

由于 promises 只能解决一次(要么满足 拒绝),第一个解决方案获胜并且任何进一步的调用都将被忽略.来自文档:

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:

在承诺解决的所有情况下(即完成或拒绝),解决方案是永久性的,无法重置.如果承诺已经解决,则尝试调用 resolve、reject 或 notify 将是空操作.

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天全站免登陆