Skip to content

Commit 9a16d0b

Browse files
committed
Rather than take a number to do more than one thing, also accept taking a list of functions to call on each thing.
1 parent 3cb1bc0 commit 9a16d0b

File tree

1 file changed

+26
-9
lines changed

1 file changed

+26
-9
lines changed

lib/utils/async-map.js

Lines changed: 26 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,22 +2,32 @@
22
/*
33
usage:
44
5-
asyncMap(myListOfStuff, function (thing, cb) { doSomething(thing, cb) }, cb)
6-
asyncMap(list, function (l, cb) { foo(l, cb) ; bar(l, cb) }, 2, cb)
5+
// do something to a list of things
6+
asyncMap(myListOfStuff, function (thing, cb) { doSomething(thing.foo, cb) }, cb)
7+
// do more than one thing to each item
8+
asyncMap(list, fooFn, barFn, cb)
9+
// call a function that needs to go in and call the cb 3 times
10+
asyncMap(list, callsMoreThanOnce, 3, cb)
711
812
*/
913

1014
module.exports = asyncMap
1115

12-
function asyncMap (list, fn, n, cb_) {
13-
if (typeof n === "function") cb_ = n, n = 1
16+
function asyncMap (list) {
17+
var steps = Array.prototype.slice.call(arguments)
18+
, list = steps.shift() || []
19+
, cb_ = steps.pop()
1420
if (typeof cb_ !== "function") throw new Error(
1521
"No callback provided to asyncMap")
16-
if (!list || !list.length) return cb_(null, [])
17-
var data = []
22+
if (!Array.isArray(list)) list = [list]
23+
var n = (typeof steps[steps.length - 1] === "number")
24+
? steps.pop()
25+
: steps.length
26+
, data = []
1827
, errState = null
1928
, l = list.length
2029
, a = l * n
30+
if (!a) return cb_(null, [])
2131
function cb (er, d) {
2232
if (errState) return
2333
if (arguments.length > 1) data = data.concat(d)
@@ -27,13 +37,20 @@ function asyncMap (list, fn, n, cb_) {
2737
a += (list.length - l) * n
2838
l = list.length
2939
process.nextTick(function () {
30-
newList.forEach(function (ar) { fn(ar, cb) })
40+
newList.forEach(function (ar) {
41+
steps.forEach(function (fn) { fn(ar, cb) })
42+
})
3143
})
3244
}
45+
// allow the callback to return boolean "false" to indicate
46+
// that an error should not tank the process.
3347
if (er) {
3448
if (false === cb_(errState = er, data)) errState = null
3549
} else if (-- a === 0) cb_(errState, data)
3650
}
37-
list.forEach(function (ar) { fn(ar, cb) })
51+
// expect the supplied cb function to be called
52+
// "n" times for each thing in the array.
53+
list.forEach(function (ar) {
54+
steps.forEach(function (fn) { fn(ar, cb) })
55+
})
3856
}
39-

0 commit comments

Comments
 (0)