Skip to content

Instantly share code, notes, and snippets.

@ollar
Last active February 3, 2017 11:38
Show Gist options
  • Save ollar/7c8c341d11de9b78bdbc15c55e4ce9cc to your computer and use it in GitHub Desktop.
Save ollar/7c8c341d11de9b78bdbc15c55e4ce9cc to your computer and use it in GitHub Desktop.
function parallel() {
let args = Array.prototype.slice.call(arguments);
let length = args.length;
let funcsComplete = 0;
let resFunc;
let results = [];
function complete(res) {
funcsComplete += 1;
results.push(res);
checkAllComplete();
}
function checkAllComplete(fn) {
if (funcsComplete === length) {
resFunc(results);
}
}
return function(fn) {
resFunc = fn;
args.forEach((_fn) => {
setTimeout(_fn.bind(null, complete), 0);
});
return checkAllComplete();
};
}
function a(cb) {
console.log('func a start');
setTimeout(() => {
console.log('func a stop');
return cb(1);
}, 1000);
}
function b(cb) {
console.log('func b start');
setTimeout(() => {
console.log('func b stop');
return cb(2);
}, 2000);
}
function c(cb) {
console.log('func c start');
setTimeout(() => {
console.log('func c stop');
return cb(3);
}, 1500);
}
function d(cb) {
console.log('func d start');
setTimeout(() => {
console.log('func d stop');
return cb(2);
}, 200);
}
parallel(a, b, c, d)((results) => console.log('yes', results));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment