mirror of
https://github.com/coderaiser/cloudcmd.git
synced 2026-07-20 01:47:35 +00:00
feature(util) exec.parallel: add ability to take and return object
This commit is contained in:
parent
af209c0fe4
commit
f8a564f2c8
1 changed files with 49 additions and 21 deletions
70
lib/util.js
70
lib/util.js
|
|
@ -823,36 +823,64 @@
|
|||
};
|
||||
|
||||
exec.parallel = function(funcs, callback) {
|
||||
var errorWas,
|
||||
var keys = [],
|
||||
callbackWas = false,
|
||||
arr = [],
|
||||
obj = {},
|
||||
count = 0,
|
||||
allData = [null],
|
||||
func = exec.ret(callback),
|
||||
funcsCount = funcs.length;
|
||||
|
||||
funcs.forEach(function(func, num) {
|
||||
exec(func, function() {
|
||||
checkFunc(num + 1, arguments);
|
||||
});
|
||||
});
|
||||
countFuncs = 0,
|
||||
type = Util.getType(funcs);
|
||||
|
||||
function checkFunc(num, data) {
|
||||
Util.checkArgs(arguments, ['funcs', 'callback']);
|
||||
|
||||
switch(type) {
|
||||
case 'array':
|
||||
countFuncs = funcs.length;
|
||||
|
||||
funcs.forEach(function(func, num) {
|
||||
exec(func, function() {
|
||||
checkFunc(num, arguments, arr);
|
||||
});
|
||||
});
|
||||
break;
|
||||
|
||||
case 'object':
|
||||
keys = Object.keys(funcs);
|
||||
countFuncs = keys.length;
|
||||
|
||||
keys.forEach(function(name) {
|
||||
var func = funcs[name];
|
||||
|
||||
exec(func, function() {
|
||||
checkFunc(name, arguments, obj);
|
||||
});
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
function checkFunc(num, data, all) {
|
||||
var args = Util.slice(data, 1),
|
||||
isLast = false,
|
||||
error = data[0],
|
||||
length = args.length;
|
||||
|
||||
if (error) {
|
||||
errorWas = true;
|
||||
func(error);
|
||||
} else if (!errorWas) {
|
||||
++count;
|
||||
|
||||
++count;
|
||||
|
||||
isLast = count === countFuncs;
|
||||
|
||||
if (!error)
|
||||
if (length >= 2)
|
||||
allData[num] = args;
|
||||
all[num] = args;
|
||||
else
|
||||
allData[num] = args[0];
|
||||
all[num] = args[0];
|
||||
|
||||
if (!callbackWas && error || isLast) {
|
||||
callbackWas = true;
|
||||
|
||||
if (count === funcsCount)
|
||||
func.apply(null, allData);
|
||||
if (type === 'array')
|
||||
callback.apply(null, [error].concat(all));
|
||||
else
|
||||
callback(error, all);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue