async-map-ordered.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. throw new Error("TODO: Not yet implemented.")
  2. /*
  3. usage:
  4. Like asyncMap, but only can take a single cb, and guarantees
  5. the order of the results.
  6. */
  7. module.exports = asyncMapOrdered
  8. function asyncMapOrdered (list, fn, cb_) {
  9. if (typeof cb_ !== "function") throw new Error(
  10. "No callback provided to asyncMapOrdered")
  11. if (typeof fn !== "function") throw new Error(
  12. "No map function provided to asyncMapOrdered")
  13. if (list === undefined || list === null) return cb_(null, [])
  14. if (!Array.isArray(list)) list = [list]
  15. if (!list.length) return cb_(null, [])
  16. var errState = null
  17. , l = list.length
  18. , a = l
  19. , res = []
  20. , resCount = 0
  21. , maxArgLen = 0
  22. function cb (index) { return function () {
  23. if (errState) return
  24. var er = arguments[0]
  25. var argLen = arguments.length
  26. maxArgLen = Math.max(maxArgLen, argLen)
  27. res[index] = argLen === 1 ? [er] : Array.apply(null, arguments)
  28. // see if any new things have been added.
  29. if (list.length > l) {
  30. var newList = list.slice(l)
  31. a += (list.length - l)
  32. var oldLen = l
  33. l = list.length
  34. process.nextTick(function () {
  35. newList.forEach(function (ar, i) { fn(ar, cb(i + oldLen)) })
  36. })
  37. }
  38. if (er || --a === 0) {
  39. errState = er
  40. cb_.apply(null, [errState].concat(flip(res, resCount, maxArgLen)))
  41. }
  42. }}
  43. // expect the supplied cb function to be called
  44. // "n" times for each thing in the array.
  45. list.forEach(function (ar) {
  46. steps.forEach(function (fn, i) { fn(ar, cb(i)) })
  47. })
  48. }
  49. function flip (res, resCount, argLen) {
  50. var flat = []
  51. // res = [[er, x, y], [er, x1, y1], [er, x2, y2, z2]]
  52. // return [[x, x1, x2], [y, y1, y2], [undefined, undefined, z2]]