1 | import wait from './wait.js';
|
2 |
|
3 | /**
|
4 | * Calls an async callback for a range of numbers.
|
5 | *
|
6 | * @example
|
7 | * ``` javascript
|
8 | * import { forRange } from 'async-agent';
|
9 | *
|
10 | * const output = [];
|
11 | *
|
12 | * forRange(3, 10, (index) => new Promise((resolve) => {
|
13 | * output.push(index);
|
14 | * resolve();
|
15 | * })
|
16 | * .then(() => {
|
17 | * console.log(output);
|
18 | * }
|
19 | *
|
20 | * // => [3, 4, 5, 6, 7, 8, 9, 10]
|
21 | *
|
22 | * const outputRight = [];
|
23 | *
|
24 | * forRange(10, 3, (index) => new Promise((resolve, reject) => {
|
25 | * outputRight.push(index);
|
26 | * if (index === 7) {
|
27 | * reject();
|
28 | * }
|
29 | * else {
|
30 | * resolve();
|
31 | * }
|
32 | * })
|
33 | * .then(() => {
|
34 | * console.log(outputRight);
|
35 | * }
|
36 | *
|
37 | * // => [10, 9, 8, 7]
|
38 | * ```
|
39 | *
|
40 | * @function forRange
|
41 | * @category Iteration
|
42 | *
|
43 | * @arg {Integer} first - The first number passed to the callback
|
44 | * @arg {Integer} last - The last number passed to the callback
|
45 | * @arg {Function} callback - Must return a promise. If this promise is rejected then iteration stops and the returned promise is resolved.
|
46 | *
|
47 | * @returns {Promise} The promise is resolved after every callback is resolved or one is rejected.
|
48 | */
|
49 | export default (first, last, callback) => wait((resolve) => {
|
50 | const isRight = first > last;
|
51 |
|
52 | const loop = (index) => {
|
53 | if (isRight ? index < last : index > last) {
|
54 | resolve();
|
55 | }
|
56 | else {
|
57 | callback(index)
|
58 | .then(() => loop(isRight ? --index : ++index))
|
59 | .catch(resolve);
|
60 | }
|
61 | };
|
62 |
|
63 | loop(first);
|
64 | });
|