Last active
February 3, 2017 11:38
-
-
Save ollar/7c8c341d11de9b78bdbc15c55e4ce9cc to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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