wishthis/node_modules/async-each/index.js

40 lines
1.3 KiB
JavaScript
Raw Normal View History

2023-02-08 12:35:10 +00:00
/*! async-each - MIT License (c) 2016 Paul Miller (paulmillr.com) */
(function (globals) {
2022-01-21 08:28:41 +00:00
'use strict';
2023-02-08 12:35:10 +00:00
var each = function (items, next, callback) {
2022-01-21 08:28:41 +00:00
if (!Array.isArray(items)) throw new TypeError('each() expects array as first argument');
2023-02-08 12:35:10 +00:00
if (typeof next !== 'function')
throw new TypeError('each() expects function as second argument');
2022-01-21 08:28:41 +00:00
if (typeof callback !== 'function') callback = Function.prototype; // no-op
2023-02-08 12:35:10 +00:00
var total = items.length;
if (total === 0) return callback(undefined, items);
var transformed = new Array(total);
var transformedCount = 0;
2022-01-21 08:28:41 +00:00
var returned = false;
2023-02-08 12:35:10 +00:00
items.forEach(function (item, index) {
next(item, function (error, transformedItem) {
2022-01-21 08:28:41 +00:00
if (returned) return;
if (error) {
returned = true;
return callback(error);
}
transformed[index] = transformedItem;
2023-02-08 12:35:10 +00:00
transformedCount += 1; // can't use index: last item could take more time
if (transformedCount === total) return callback(undefined, transformed);
2022-01-21 08:28:41 +00:00
});
});
};
if (typeof define !== 'undefined' && define.amd) {
2023-02-08 12:35:10 +00:00
define([], function () {
2022-01-21 08:28:41 +00:00
return each;
}); // RequireJS
} else if (typeof module !== 'undefined' && module.exports) {
module.exports = each; // CommonJS
} else {
globals.asyncEach = each; // <script>
}
})(this);