forked from Azure/login
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheachSeries.js
More file actions
52 lines (47 loc) · 1.25 KB
/
Copy patheachSeries.js
File metadata and controls
52 lines (47 loc) · 1.25 KB
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
import { _setImmediate } from './_setImmediate'
/**
* Run `items` on async `task` function in series. Stops at the first error encountered.
*
* @name eachSeries
* @memberOf module:serial
* @static
* @method
* @param {Array<any>} items - Array of items
* @param {Function} task - iterator function of type `function (item: any, cb: Function, index: Number)`
* @param {Function} [callback] - optional callback `function (errors: <Error>, result: Array<any>)`
* @example
* eachSeries([1, 2, 3],
* (item, cb, index) => {
* setImmediate(() => {
* cb(index % 2 ? null : 'error', item + index)
* })
* }, (err, res) => {
* //> err = 'error'
* //> res = [1, 4]
* }
* )
*/
export default function eachSeries (items, task, callback) {
const length = items.length
const results = []
let i = 0
if (length === 0) {
callback(null, [])
return
}
run()
function cb (err, res) {
results.push(res)
/* istanbul ignore else */
if (err || length === i) {
callback && callback(err, results)
} else if (i < length) {
_setImmediate(() => { // prevent RangeError: Maximum call stack size exceeded for sync tasks
run()
})
}
}
function run () {
task(items[i], cb, i++)
}
}