• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1'use strict';
2
3var errcode = require('err-code');
4var retry = require('retry');
5
6var hasOwn = Object.prototype.hasOwnProperty;
7
8function isRetryError(err) {
9    return err && err.code === 'EPROMISERETRY' && hasOwn.call(err, 'retried');
10}
11
12function promiseRetry(fn, options) {
13    var temp;
14    var operation;
15
16    if (typeof fn === 'object' && typeof options === 'function') {
17        // Swap options and fn when using alternate signature (options, fn)
18        temp = options;
19        options = fn;
20        fn = temp;
21    }
22
23    operation = retry.operation(options);
24
25    return new Promise(function (resolve, reject) {
26        operation.attempt(function (number) {
27            Promise.resolve()
28            .then(function () {
29                return fn(function (err) {
30                    if (isRetryError(err)) {
31                        err = err.retried;
32                    }
33
34                    throw errcode('Retrying', 'EPROMISERETRY', { retried: err });
35                }, number);
36            })
37            .then(resolve, function (err) {
38                if (isRetryError(err)) {
39                    err = err.retried;
40
41                    if (operation.retry(err || new Error())) {
42                        return;
43                    }
44                }
45
46                reject(err);
47            });
48        });
49    });
50}
51
52module.exports = promiseRetry;
53