mapSeries.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. if (length === 0) {
  23. return done(null, results);
  24. }
  25. var key = keys[idx];
  26. next(key);
  27. function next(key) {
  28. var value = values[key];
  29. var storage = exts.create(value, key) || {};
  30. exts.before(storage);
  31. iterator(value, key, once(handler));
  32. function handler(err, result) {
  33. if (err) {
  34. exts.error(err, storage);
  35. return done(err, results);
  36. }
  37. exts.after(result, storage);
  38. results[key] = result;
  39. if (++idx >= length) {
  40. done(err, results);
  41. } else {
  42. next(keys[idx]);
  43. }
  44. }
  45. }
  46. }
  47. module.exports = mapSeries;