tim-kos/node-retry

Callback gets executed multiple times when retrying function succeeds

mtchllbrrn opened this issue · 2 comments

It looks like each attempt calls the callback when the connection finally succeeds. The desired behavior is for the callback to be called once.

// Open the DDP connection
function connectDDPWithRetry(ddpConnection, cb) {
  const operation = retry.operation();

  operation.attempt((currentAttempt) => {
    console.log(`executing. attempt #${currentAttempt}`); /* eslint no-console:0 */
    ddpConnection.connect(err => {
      if (err) {
        operation.retry(err);
      } else {
        console.log('calling CB');
        cb();
      }
    });
  });
}

connectDDPWithRetry(ddp, (err) => {
  console.log('inside callback');
  if (err) throw err;
  const { JOB_USER, JOB_PASS } = process.env;
  DDPlogin.loginWithUsername(ddp, JOB_USER, JOB_PASS, err2 => {
    if (err2) throw err2;
    console.log('CONNECTED');
    Job.processJobs('jobs', 'fooJob', (job, cb) => {
      // This will only be called if a fooJob job is obtained
      console.log(job.data); /* eslint no-console: 0 */
      job.done();
      cb();
    });
  });
});
executing. attempt #1
executing. attempt #2
executing. attempt #3
executing. attempt #4
executing. attempt #5
executing. attempt #6
calling CB
inside callback
calling CB
inside callback
calling CB
inside callback
calling CB
inside callback
calling CB
inside callback
calling CB
inside callback
CONNECTED
CONNECTED
CONNECTED
CONNECTED
Login failed: Error, too many requests. Please slow down. You must wait 9 seconds before trying again. [too-many-requests]
./fooWorker.js:43
    if (err2) throw err2;
              ^

perhaps instead of

if (err) {
operation.retry(err);

}

if (operation.retry(err)) {
return;
}

I don't think an attempt was ever registered, and so some rule will cause it to refire.

Yes you need to pass the err to `operation.retry' like in the examples in the Readme. That will fix it.