使用节点确定成功/失败.js函数 async.retry

Determining success/failure with node.js function async.retry

本文关键字:js 失败 函数 async retry 成功 节点      更新时间:2023-09-26

我正在研究node.js模块异步,但我对函数async.retry有一些问题。

根据其github文档,该函数将继续尝试该任务,直到成功或机会用完。但是我的任务如何判断成功或失败?

我尝试了下面的代码:

var async = require('async');
var opts = {
    count : -3
};
async.retry(5, function (cb, results) {
    ++this.count;
    console.log(this.count, results);
    if (this.count > 0) cb(null, this.count);
    else cb();
}.bind(opts), function (err, results) {
   console.log(err, results);
});

我希望它运行到 count === 1 ,但它总是打印以下内容:

-2 undefined
undefined undefined

那么如何才能正确使用该功能呢?

您希望else分支失败。为此,您需要向错误参数传递一些内容;目前,你只是传递undefined这标志着成功 - 这就是你得到的回报。

async.retry(5, function (cb, results) {
    ++this.count;
    console.log(this.count, results);
    if (this.count > 0) cb(null, this.count);
    else cb(new Error("count too low"));
}.bind(opts), function (err, results) {
   console.log(err, results);
});