Determining success/failure with node.js function async.retry
Asked Answered
S

1

11

I'm studying the node.js module async, but I have some problems with the function async.retry.

According to its github docs, the function will continue trying the task until it succeeds or chances are used up. But how can my task tell success or failure?

I tried the code below:

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);
});

I expect it to run until count === 1, but it always prints this:

-2 undefined
undefined undefined

So how can I use the function correctly?

Siltstone answered 11/3, 2015 at 2:39 Comment(1)
Thank you for showing the use of bind in the async task. I was just trying to figure out how to pass arguments.Graham
T
5

You want your else-branch to fail. For that, you need to pass something to the error parameter; currently you just pass undefined which signals success - and that's what you get back.

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);
});
Tabu answered 11/3, 2015 at 3:17 Comment(2)
What completely escapes me is why it's not in the documentation that the callback should be the first parameter of the function you're retrying.Graham
@Ali: Uh, actually it's right there: "task(callback, results) - A function which receives two arguments: (1) a callback …"Tabu

© 2022 - 2024 — McMap. All rights reserved.