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

Yao*_*hao 10 javascript asynchronous node.js node-async

我正在研究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);
});
Run Code Online (Sandbox Code Playgroud)

我希望它能一直运行count === 1,但它总会打印出来:

-2 undefined
undefined undefined
Run Code Online (Sandbox Code Playgroud)

那我怎么能正确使用这个功能呢?

Ber*_*rgi 5

你希望你的else-branch失败.为此,您需要将一些内容传递给error参数; 目前你只是传递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);
});
Run Code Online (Sandbox Code Playgroud)

  • @Ali:呃,实际上它是 [就在那里](https://github.com/caolan/async#retry):"*`task(callback, results)` - 一个接收两个参数的函数:(1) 一个回调……*” (2认同)