async-map.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /*
  2. usage:
  3. // do something to a list of things
  4. asyncMap(myListOfStuff, function (thing, cb) { doSomething(thing.foo, cb) }, cb)
  5. // do more than one thing to each item
  6. asyncMap(list, fooFn, barFn, cb)
  7. */
  8. module.exports = asyncMap
  9. function asyncMap () {
  10. var steps = Array.prototype.slice.call(arguments)
  11. , list = steps.shift() || []
  12. , cb_ = steps.pop()
  13. if (typeof cb_ !== "function") throw new Error(
  14. "No callback provided to asyncMap")
  15. if (!list) return cb_(null, [])
  16. if (!Array.isArray(list)) list = [list]
  17. var n = steps.length
  18. , data = [] // 2d array
  19. , errState = null
  20. , l = list.length
  21. , a = l * n
  22. if (!a) return cb_(null, [])
  23. function cb (er) {
  24. if (er && !errState) errState = er
  25. var argLen = arguments.length
  26. for (var i = 1; i < argLen; i ++) if (arguments[i] !== undefined) {
  27. data[i - 1] = (data[i - 1] || []).concat(arguments[i])
  28. }
  29. // see if any new things have been added.
  30. if (list.length > l) {
  31. var newList = list.slice(l)
  32. a += (list.length - l) * n
  33. l = list.length
  34. process.nextTick(function () {
  35. newList.forEach(function (ar) {
  36. steps.forEach(function (fn) { fn(ar, cb) })
  37. })
  38. })
  39. }
  40. if (--a === 0) cb_.apply(null, [errState].concat(data))
  41. }
  42. // expect the supplied cb function to be called
  43. // "n" times for each thing in the array.
  44. list.forEach(function (ar) {
  45. steps.forEach(function (fn) { fn(ar, cb) })
  46. })
  47. }