UNPKG

1.36 kBJavaScriptView Raw
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
10 var total = items.length;
11 if (total === 0) return callback(undefined, items);
12 var transformed = new Array(total);
13 var transformedCount = 0;
14 var returned = false;
15
16 items.forEach(function (item, index) {
17 next(item, function (error, transformedItem) {
18 if (returned) return;
19 if (error) {
20 returned = true;
21 return callback(error);
22 }
23 transformed[index] = transformedItem;
24 transformedCount += 1; // can't use index: last item could take more time
25 if (transformedCount === total) return callback(undefined, transformed);
26 });
27 });
28 };
29
30 if (typeof define !== 'undefined' && define.amd) {
31 define([], function () {
32 return each;
33 }); // RequireJS
34 } else if (typeof module !== 'undefined' && module.exports) {
35 module.exports = each; // CommonJS
36 } else {
37 globals.asyncEach = each; // <script>
38 }
39})(this);