index.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. /*! async-each - MIT License (c) 2016 Paul Miller (paulmillr.com) */
  2. (function (globals) {
  3. 'use strict';
  4. var each = function (items, next, callback) {
  5. if (!Array.isArray(items)) throw new TypeError('each() expects array as first argument');
  6. if (typeof next !== 'function')
  7. throw new TypeError('each() expects function as second argument');
  8. if (typeof callback !== 'function') callback = Function.prototype; // no-op
  9. var total = items.length;
  10. if (total === 0) return callback(undefined, items);
  11. var transformed = new Array(total);
  12. var transformedCount = 0;
  13. var returned = false;
  14. items.forEach(function (item, index) {
  15. next(item, function (error, transformedItem) {
  16. if (returned) return;
  17. if (error) {
  18. returned = true;
  19. return callback(error);
  20. }
  21. transformed[index] = transformedItem;
  22. transformedCount += 1; // can't use index: last item could take more time
  23. if (transformedCount === total) return callback(undefined, transformed);
  24. });
  25. });
  26. };
  27. if (typeof define !== 'undefined' && define.amd) {
  28. define([], function () {
  29. return each;
  30. }); // RequireJS
  31. } else if (typeof module !== 'undefined' && module.exports) {
  32. module.exports = each; // CommonJS
  33. } else {
  34. globals.asyncEach = each; // <script>
  35. }
  36. })(this);