parallel.js 1017 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. var iterate = require('./lib/iterate.js')
  2. , initState = require('./lib/state.js')
  3. , terminator = require('./lib/terminator.js')
  4. ;
  5. // Public API
  6. module.exports = parallel;
  7. /**
  8. * Runs iterator over provided array elements in parallel
  9. *
  10. * @param {array|object} list - array or object (named list) to iterate over
  11. * @param {function} iterator - iterator to run
  12. * @param {function} callback - invoked when all elements processed
  13. * @returns {function} - jobs terminator
  14. */
  15. function parallel(list, iterator, callback)
  16. {
  17. var state = initState(list);
  18. while (state.index < (state['keyedList'] || list).length)
  19. {
  20. iterate(list, iterator, state, function(error, result)
  21. {
  22. if (error)
  23. {
  24. callback(error, result);
  25. return;
  26. }
  27. // looks like it's the last one
  28. if (Object.keys(state.jobs).length === 0)
  29. {
  30. callback(null, state.results);
  31. return;
  32. }
  33. });
  34. state.index++;
  35. }
  36. return terminator.bind(state, callback);
  37. }