使用node.js函数确定成功/失败的函数async.retry
我正在研究node.js模块的asynchronous,但我有一些async.retry函数的问题。
根据其github文档 ,该function将继续尝试任务,直到成功或机会用完。 但是我的任务怎么能告诉成功或失败呢?
我试了下面的代码:
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
那我该如何正确使用这个function?
你想要你的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); });