UNPKG

993 BJavaScriptView Raw
1var co = require('./common.js')
2
3module.exports = function (collections, limit, func) {
4 // prepare input map
5 var ins = {} // inputs
6 co.map(collections, function (i, k) {
7 ins[k] = i
8 })
9
10 // normalize limit
11 if (limit <= 0) limit = 1
12 if (Object.keys(ins).length < limit) limit = Object.keys(ins).length
13
14 var outs = {} // outputs
15
16 return new Promise(function (resolve) {
17 var doJob = function () {
18 var keys = Object.keys(ins)
19 if (keys.length === 0) return
20
21 var key = keys.pop()
22 var value = ins[key]
23 delete ins[key]
24
25 var amITheLast = keys.length === 0
26
27 var pro = func(value, key)
28
29 // func return result instead of a promise
30 // we treat the out put as a promise
31 if (!pro.then) {
32 var out = pro
33 pro = {
34 then: function (f) {
35 return f(out)
36 },
37 }
38 }
39
40 pro.then(function (ret) {
41 outs[key] = ret
42 if (amITheLast) return resolve(co.map(outs))
43
44 doJob()
45 })
46 }
47
48 for (var i = 0; i < limit; i++) setTimeout(doJob, 1)
49 })
50}