2
2
/*
3
3
usage:
4
4
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)
7
11
8
12
*/
9
13
10
14
module . exports = asyncMap
11
15
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 ( )
14
20
if ( typeof cb_ !== "function" ) throw new Error (
15
21
"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 = [ ]
18
27
, errState = null
19
28
, l = list . length
20
29
, a = l * n
30
+ if ( ! a ) return cb_ ( null , [ ] )
21
31
function cb ( er , d ) {
22
32
if ( errState ) return
23
33
if ( arguments . length > 1 ) data = data . concat ( d )
@@ -27,13 +37,20 @@ function asyncMap (list, fn, n, cb_) {
27
37
a += ( list . length - l ) * n
28
38
l = list . length
29
39
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
+ } )
31
43
} )
32
44
}
45
+ // allow the callback to return boolean "false" to indicate
46
+ // that an error should not tank the process.
33
47
if ( er ) {
34
48
if ( false === cb_ ( errState = er , data ) ) errState = null
35
49
} else if ( -- a === 0 ) cb_ ( errState , data )
36
50
}
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
+ } )
38
56
}
39
-
0 commit comments