現在我正在學習如何使用promise
編寫JavaScript代碼。這裏是我的情況,Sender
中的deliverMessage
函數嘗試與amqp連接。如果成功,則撥打publish_
發送消息。否則,請在3秒鐘後致電reconnect_
重新連接至amqp
。該代碼如下,Promise中的遞歸重試
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
來實現它嗎?
你嘗試過'''。然後(this.handleDisconnections_)。然後(this.publish_,this.reconnect_) '''? – mido 2015-02-11 01:16:19
@ mido22 - 但可能需要一些東西,不會讓這個循環永遠每隔3秒重試一次。在放棄之前可能是最大數量的重試。 – jfriend00 2015-02-11 01:23:07
@ jfriend00現在我的答案,我已經添加了一個參數來照顧的嘗試次數... – mido 2015-02-11 01:31:29