From 2b4f5b858479fc2f433499424207955a48c6bf75 Mon Sep 17 00:00:00 2001 From: Guillermo Rauch Date: Sat, 27 Feb 2016 16:36:41 -0800 Subject: [PATCH] retry: wrap node-retry and make it `await`-friendly --- lib/retry.js | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 lib/retry.js diff --git a/lib/retry.js b/lib/retry.js new file mode 100644 index 0000000..79e37df --- /dev/null +++ b/lib/retry.js @@ -0,0 +1,29 @@ +import retrier from 'retry'; + +export default function retry (fn, opts) { + return new Promise((resolve, reject) => { + const op = retrier.operation(opts); + const { onRetry } = opts; + + // we allow the user to abort retrying + // this makes sense in the cases where + // knowledge is obtained that retrying + // would be futile (e.g.: auth errors) + const bail = (err) => reject(err); + + op.attempt((num) => { + if (num > 1 && onRetry) { + const errs = op.errors(); + onRetry(errs[errs.length - 1]); + } + + fn(bail) + .then((val) => resolve(val)) + .catch(err => { + if (!op.retry(err)) { + reject(op.mainError()); + } + }); + }); + }); +}