mapSeries.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. 'use strict';
  2. var once = require('once');
  3. var helpers = require('./helpers');
  4. function mapSeries(values, iterator, extensions, done) {
  5. // Allow for extensions to not be specified
  6. if (typeof extensions === 'function') {
  7. done = extensions;
  8. extensions = {};
  9. }
  10. // Handle no callback case
  11. if (typeof done !== 'function') {
  12. done = helpers.noop;
  13. }
  14. done = once(done);
  15. // Will throw if non-object
  16. var keys = Object.keys(values);
  17. var length = keys.length;
  18. var idx = 0;
  19. // Return the same type as passed in
  20. var results = helpers.initializeResults(values);
  21. var exts = helpers.defaultExtensions(extensions);
  22. var key = keys[idx];
  23. next(key);
  24. function next(key) {
  25. var value = values[key];
  26. var storage = exts.create(value, key) || {};
  27. exts.before(storage);
  28. iterator(value, key, once(handler));
  29. function handler(err, result) {
  30. if (err) {
  31. exts.error(err, storage);
  32. return done(err, results);
  33. }
  34. exts.after(result, storage);
  35. results[key] = result;
  36. if (++idx >= length) {
  37. done(err, results);
  38. } else {
  39. next(keys[idx]);
  40. }
  41. }
  42. }
  43. }
  44. module.exports = mapSeries;