Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * runs callbacks in parallel and returns once all callbacks are executed
- * accept arguments as array f function or object of a function
- * should be called in form of array of object of following function
- * const tasks = [function yourName(callback) {
- * your_function(a, b, c, (data) => {
- * callback(null, data);
- * })
- * },]
- * You are able to access above data as
- * executeParallel(tasks, (err, results) => {
- * const data = results.yourName; // your function name
- * })
- */
- export const executeParallel = function (tasks, cb) {
- let results;
- let pending;
- let keys;
- let isSync = true;
- if (Array.isArray(tasks)) {
- results = {};
- pending = tasks.length;
- } else {
- keys = Object.keys(tasks);
- results = {};
- pending = keys.length;
- }
- function done (err) {
- function end () {
- if (cb) cb(err, results);
- cb = null;
- }
- if (isSync) process.nextTick(end);
- else end();
- }
- function each (i, err, result, name) {
- results[name] = result;
- if (--pending === 0 || err) {
- done(err);
- }
- }
- if (!pending) {
- // empty
- done(null);
- } else if (keys) {
- // object
- keys.forEach(function (key) {
- tasks[key](function (err, result) { each(key, err, result) });
- })
- } else {
- // array
- tasks.forEach(function (task, i) {
- task(function (err, result) { each(i, err, result, task.name) });
- })
- }
- isSync = false;
- }
Add Comment
Please, Sign In to add comment