forked from vercel/async-retry
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
131 lines (110 loc) · 2.4 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
// Packages
const test = require('ava');
const fetch = require('node-fetch');
const sleep = require('then-sleep');
// Ours
const retry = require('../lib');
test('return value', async t => {
const val = await retry(async (bail, num) => {
if (num < 2) {
throw new Error('woot');
}
await sleep(50);
return `woot ${num}`;
});
t.deepEqual('woot 2', val);
});
test('return value no await', async t => {
const val = await retry(async (bail, num) => num);
t.deepEqual(1, val);
});
test('chained promise', async t => {
const res = await retry(async (bail, num) => {
if (num < 2) {
throw new Error('retry');
}
return fetch('https://www.wikipedia.org');
});
t.deepEqual(200, res.status);
});
test('bail', async t => {
try {
await retry(
async (bail, num) => {
if (num === 2) {
bail(new Error('Wont retry'));
}
throw new Error(`Test ${num}`);
},
{ retries: 3 }
);
} catch (err) {
t.deepEqual('Wont retry', err.message);
}
});
test('bail + return', async t => {
let error;
try {
await Promise.resolve(
retry(async bail => {
await sleep(200);
await sleep(200);
bail(new Error('woot'));
})
);
} catch (err) {
error = err;
}
t.deepEqual(error.message, 'woot');
});
test('bail error', async t => {
let retries = 0;
try {
await retry(
async () => {
retries += 1;
await sleep(100);
const err = new Error('Wont retry');
err.bail = true;
throw err;
},
{ retries: 3 }
);
} catch (err) {
t.deepEqual('Wont retry', err.message);
}
t.deepEqual(retries, 1);
});
test('with non-async functions', async t => {
try {
await retry(
(bail, num) => {
throw new Error(`Test ${num}`);
},
{ retries: 2 }
);
} catch (err) {
t.deepEqual('Test 3', err.message);
}
});
test('return non-async', async t => {
const val = await retry(() => 5);
t.deepEqual(5, val);
});
test('with number of retries', async t => {
let retries = 0;
try {
await retry(() => fetch('https://www.fakewikipedia.org'), {
retries: 2,
onRetry: (err, i) => {
if (err) {
// eslint-disable-next-line no-console
console.log('Retry error : ', err);
}
retries = i;
}
});
} catch (err) {
t.deepEqual(retries, 2);
}
});