Skip to content

Instantly share code, notes, and snippets.

@TehShrike
Created December 19, 2012 06:58
Show Gist options
  • Save TehShrike/4334955 to your computer and use it in GitHub Desktop.
Save TehShrike/4334955 to your computer and use it in GitHub Desktop.
Two ways to find out when all your async stuff is done
// Imagine that this is somebody else's async tool that you're using
var doAsyncThing = function(thing, cb) {
cb(thing + '!')
}
// So you have this utility function
var callThisWhenTheThingsAreDone = function(callback, number_of_things_to_do) {
var things_done = 0
return function() {
things_done++
if (number_of_things_to_do === things_done) {
callback()
}
}
}
// And this is the thing that happens once all the async stuff is done
var finisher = function() {
console.log("ALL DONE!")
}
// So, you can just do this
var things_to_work_on = ['what', 'what', 'in', 'the', 'butt']
var thingFinished = callThisWhenTheThingsAreDone(finisher, things_to_work_on.length)
things_to_work_on.forEach(function(thing) {
doAsyncThing(thing, function(result) {
console.log("I got back " + result)
thingFinished()
})
})
var doAsyncThing = function(thing, cb) {
cb(thing + '!')
}
var finisher = function() {
console.log("ALL DONE!")
}
var things_to_work_on = ['what', 'what', 'in', 'the', 'butt']
var things_done = 0
things_to_work_on.forEach(function(thing) {
doAsyncThing(thing, function(result) {
console.log("I got back " + result)
things_done++
if (things_done === things_to_work_on.length) {
finisher()
}
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment