gpt4 book ai didi

javascript - Promise 中的递归重试

转载 作者:行者123 更新时间:2023-11-30 08:39:08 31 4
gpt4 key购买 nike

现在我正在学习如何使用 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 实现它?

最佳答案

我会那样做...

Sender.prototype.reconnect_ = function( err, attempt ) {
attempt = attempt || 0;
attempt++;
if(attempt>3){ // change it to whatever value you prefer
throw err;
}
console.error('MessageBus disconnected, attempting to reconnect' + err);
this.createFakeChannel_();
return setTimeout( this.deliverMessage.bind(this, attempt ), 3000);
};
Sender.prototype.deliverMessage = function(attempt) {
when(amqp.connect( this.addr_ ))
.with( this )
.then( this.createChannel_ )
.then( this.createExchange_ )
.then( this.handleUnrouteableMessages_ )
.then( this.handleDisconnections_ )
.then( this.publish_, function(err){
this.reconnect_(err, attempt);
});
};

关于javascript - Promise 中的递归重试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28444895/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com