-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
57 lines (44 loc) · 1.23 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
'use strict'
const combine = require('maybe-combine-errors')
module.exports = function parallel (tasks, limit, callback) {
if (typeof limit === 'function') {
return parallel(tasks, Infinity, limit)
}
if (typeof limit !== 'number' || limit < 1) {
throw new TypeError('The "limit" argument must be a number >= 1')
}
const length = tasks.length
const results = new Array(length)
if (length === 0) return process.nextTick(callback, null, results)
if (limit > length) limit = length
let pending = length
let position = limit
let errors = null
let sync = true
for (let i = 0; i < limit; i++) {
tasks[i](next.bind(null, i))
}
sync = false
function next (i, err, result) {
if (err) {
if (errors === null) {
errors = new Array(length)
pending -= length - position
}
errors[i] = err
} else if (errors === null) {
results[i] = result
}
if (--pending === 0) {
done()
} else if (errors === null && position < length) {
const i = position++
tasks[i](next.bind(null, i))
}
}
function done () {
if (sync) return process.nextTick(done)
if (errors !== null) return callback(combine(errors))
callback(null, results)
}
}