tim-kos/node-retry

Reuse operation instance

nfantone opened this issue ยท 4 comments

I've run into a use case where I'd like to reuse a previously created retry.operation. Upon some errors, I'd like to restart the whole operation from scratch, exactly as if a new operation would have been created. The reason why creating an actual new retry.operation() is inconvenient is because the function being retried contains a reference to the operation and uses it to call op.retry and, basically, retry itself. So while I could potentially refactor my module to avoid this, it would be much simpler to just do something along the lines of:

function onError(err, op) {
  log('some error occurred', err);
  // Reset operation internal state -> start anew
  op.reset();
  return op.retry(err);
}

let op = retry.operation();
op.attempt(function() {
  getSomeResource().then((res) => {
    res.on('error', (err) => onError(err, op));
    // Do something with resource
    // ...
  }).catch((err) => {
    // Retry operation normally
    if (!op.retry(err)) return;
  });
});

Any thoughts on this? Can this be done, currently?

op._attempts = 1;
op._timeouts = retry.timeouts(op._options);

That would be a very basic implementation of .reset(). I've tried it and it seems to work. It's hacky, though.

@tim-kos Up for a PR?

Yup, sounds good. Please send a PR, then I will review and maybe come up with a less hacky version. ๐Ÿ‘

Hey @nfantone

Do you still plan to send this PR one year later. :)

@tim-kos Hey. I think it's fair to say that I completely forgot about this ๐Ÿ˜†.

GJ and thanks!