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