Created
March 6, 2015 11:29
-
-
Save lesha-co/46205c712dfd586420ed to your computer and use it in GitHub Desktop.
my first async lib
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
magic([taskA, taskB, taskC], [taskD], [taskE, taskF], [taskG]); // see magic.js main() | |
/* | |
each task is a function like this: | |
function taskA(param1, param2, param3 ) { // arbitary number of params | |
return function (fCallback) { | |
setTimeout(function(){ | |
fCallback (null, param1); // error, result | |
}, param1) | |
}; | |
} | |
The tasks execute in this scenario | |
1. a,b,c simultaneously | |
2. d | |
3. e,f simultaneously | |
4. g -- you can use last task as a callback from this whole operation | |
*/ | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"use strict"; | |
function serial(arr) { | |
//console.log("serial started"); | |
function next(err, result) { | |
//console.log('serialResult\n\t', result); | |
//console.log(" --> next"); | |
if (err) { | |
throw err; | |
} | |
var currentTask = arr.shift(); | |
if (currentTask) { | |
currentTask(next); | |
} | |
} | |
next(null, null); | |
} | |
function getParallelDispatcher(nTasks, fCallback) { | |
var results = []; | |
var errors = []; | |
var nT = nTasks; | |
var nC = 0; | |
return function (err, result) { | |
results.push(result); | |
errors.push(err); | |
nC++; | |
if (nC === nT) { | |
fCallback(errors, results); | |
} | |
}; | |
} | |
function parallel(arr, fCallback) { | |
var i, iErrCntr, allNull = true; | |
function onComplete(errs, results) { | |
//console.log("parallel ended"); | |
for (iErrCntr = 0; iErrCntr < errs.length; iErrCntr++) { | |
if (errs[iErrCntr]) { | |
allNull = false; | |
} | |
} | |
if (allNull) { | |
fCallback(null, results); | |
} else { | |
fCallback(errs, results); | |
} | |
} | |
//console.log("parallel started"); | |
var dispatcher = getParallelDispatcher(arr.length, onComplete); | |
for (i = 0; i < arr.length; i++) { | |
arr[i](dispatcher); | |
} | |
} | |
function getNewParallel(tasks) { | |
var tsk = tasks; | |
return function (next) { | |
parallel(tsk, next); | |
}; | |
} | |
function main() { | |
var tasks = [], iArgCntr; | |
for (iArgCntr = 0; iArgCntr < arguments.length; iArgCntr++) { | |
if (arguments[iArgCntr] instanceof Array) { | |
tasks.push(getNewParallel(arguments[iArgCntr])); | |
} else { | |
tasks.push(getNewParallel([arguments[iArgCntr]])); | |
} | |
} | |
serial(tasks); | |
} | |
module.exports = main; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment