【发布时间】:2015-02-12 20:03:30
【问题描述】:
现在我正在学习如何使用 promise 编写 JavaScript 代码。这是我的情况,Sender 中的deliverMessage 函数尝试与 amqp 连接。如果成功,则调用publish_ 发送消息。否则,请在 3 秒后调用 reconnect_ 以重新连接到 amqp。代码如下,
Sender.prototype.reconnect_ = function( err ) {
console.error('MessageBus disconnected, attempting to reconnect' + err);
this.createFakeChannel_();
return setTimeout( this.deliverMessage.bind(this), 3000);
};
Sender.prototype.deliverMessage = function() {
when(amqp.connect( this.addr_ ))
.with( this )
.then( this.createChannel_ )
.then( this.createExchange_ )
.then( this.handleUnrouteableMessages_ )
.then( this.handleDisconnections_ )
.catch( this.reconnect_ )
.done( this.publish_ ); //? publish_ is invoked in all case?
};
其实不管是连接成功还是失败,publish_反正都会被调用。谁能帮我用promise 实现它?
【问题讨论】:
-
你试过
.then( this.handleDisconnections_ ).then(this.publish_, this.reconnect_)吗? -
@mido22 - 但可能需要一些不会让这个循环永远持续每 3 秒重试一次的东西。也许在放弃之前重试的最大次数。
-
@jfriend00 我现在的答案怎么样,我已经添加了一个参数来处理尝试次数...
-
catch“成功”处理了 Promise(除非它自己抛出),这意味着链式then(包括done)将对 @ 的已实现/已解决结果进行操作987654334@。如果您希望承诺“保持”在拒绝状态,一种简单的方法是在reconnect_中重新抛出错误。
标签: javascript promise