Last active
December 11, 2015 12:08
-
-
Save catdad/4598289 to your computer and use it in GitHub Desktop.
This function can be used to sync many asynchronous functions. You only have to maintain the list and order once, and they will execute one after the other, as well as a callback after all the functions are done.
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 firstFunction(next){ | |
console.log('first function'); | |
setTimeout(next, 1000); | |
} | |
function secondFunction(next){ | |
console.log('second function'); | |
setTimeout(next, 1000); | |
} | |
function sync(funcs, done){ | |
var counter = funcs.length; | |
var idx = 0; | |
var next = function() { | |
if (--counter === 0) done(); | |
else funcs[idx++](next); | |
}; | |
funcs[idx++](next); | |
} | |
function over(){ console.log('async functions are over') }; | |
sync([firstFunction, secondFunction], over); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment