在 nodejs 中重做任务,如果承诺失败直到达到 maxLimit
In nodejs redo the task if promise failed until it reach maxLimit
我有执行 NetowrkIO 的功能,但在这种情况下网络不可靠,所以第一次尝试可能无法正常工作,所以如果失败我需要重试
这是它的伪代码
count = 0
maxLimit = 10
success = false
while ( (success == false) && (count < maxLimit))
{
try
{
doNetworkIO(arg)
success = true
}
catch(ex)
{
count += 1
}
}
if( success == true )
{
reportSuccess()
} else {
reportFailure()
}
现在我正尝试在 nodejs 中进行。我搜索并提出了 promise 作为一种实现方式。但我不知道如何。
这是我的代码。
var count = 0
var maxLimit = 10
doNetworkIO(arg)
.then(reportSuccess)
.catch(function () {
if(count < maxLimit)
{
count += 1
// => redo operation if count < limit
// => help needed here
}
else {
reportFailure()
}
})
这里我不确定要重做一次。
如果您有不同的任务方法,请分享。
您可以编写一个重试函数,它将自身附加到失败处理程序中,如下所示
var count = 0;
var maxLimit = 10;
function tryNetworkIO() {
if (count < maxLimit) {
count += 1;
return doNetworkIO(arg).then(reportSuccess).catch(tryNetworkIO);
} else {
reportFailure();
}
}
受this answer的启发,你可以稍微改进一下,在最后附加一次reportSuccess
,当承诺真正解决时,像这样
var count = 0;
var maxLimit = 10;
function tryNetworkIO() {
if (++count < maxLimit) {
return doNetworkIO(arg).catch(tryNetworkIO);
} else {
throw new Error('Exceeded maximum number of retries');
}
}
tryNetworkIO().then(reportSuccess).catch(reportFailure);
我有执行 NetowrkIO 的功能,但在这种情况下网络不可靠,所以第一次尝试可能无法正常工作,所以如果失败我需要重试 这是它的伪代码
count = 0
maxLimit = 10
success = false
while ( (success == false) && (count < maxLimit))
{
try
{
doNetworkIO(arg)
success = true
}
catch(ex)
{
count += 1
}
}
if( success == true )
{
reportSuccess()
} else {
reportFailure()
}
现在我正尝试在 nodejs 中进行。我搜索并提出了 promise 作为一种实现方式。但我不知道如何。 这是我的代码。
var count = 0
var maxLimit = 10
doNetworkIO(arg)
.then(reportSuccess)
.catch(function () {
if(count < maxLimit)
{
count += 1
// => redo operation if count < limit
// => help needed here
}
else {
reportFailure()
}
})
这里我不确定要重做一次。
如果您有不同的任务方法,请分享。
您可以编写一个重试函数,它将自身附加到失败处理程序中,如下所示
var count = 0;
var maxLimit = 10;
function tryNetworkIO() {
if (count < maxLimit) {
count += 1;
return doNetworkIO(arg).then(reportSuccess).catch(tryNetworkIO);
} else {
reportFailure();
}
}
受this answer的启发,你可以稍微改进一下,在最后附加一次reportSuccess
,当承诺真正解决时,像这样
var count = 0;
var maxLimit = 10;
function tryNetworkIO() {
if (++count < maxLimit) {
return doNetworkIO(arg).catch(tryNetworkIO);
} else {
throw new Error('Exceeded maximum number of retries');
}
}
tryNetworkIO().then(reportSuccess).catch(reportFailure);