Skip to content

Instantly share code, notes, and snippets.

@melissamarima
Last active December 21, 2015 03:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save melissamarima/5d51f698a58edf92dccb to your computer and use it in GitHub Desktop.
Save melissamarima/5d51f698a58edf92dccb to your computer and use it in GitHub Desktop.
Understanding fat arrows
// https://greenin.space/how-do-you-write-an-asynchronous-for-loop-in-javascript/
var N = 5
function asyncFunc (cb) {
console.log("in asyncFunc")
setTimeout(() => cb(Math.random()), 3000)
console.log("out asyncFunc")
}
function loop (max, results, done) {
// Recursion base-case
if (results.length >= max) return done(results)
console.log("in loop")
asyncFunc((res) => {
results.push(res)
loop(max, results, done)
})
}
var randomNumbers = []
loop(N, randomNumbers, function (results) {
console.log(results)
})
/*
VM230:13 in loop
VM230:5 in asyncFunc
VM230:7 out asyncFunc
////////// pause 3 secs
VM230:13 in loop
VM230:5 in asyncFunc
VM230:7 out asyncFunc
///////// pause 3 secs
VM230:13 in loop
VM230:5 in asyncFunc
VM230:7 out asyncFunc
////////// pause 3 secs
VM230:13 in loop
VM230:5 in asyncFunc
VM230:7 out asyncFunc
//////// pause 3 secs
VM230:13 in loop
VM230:5 in asyncFunc
VM230:7 out asyncFunc
//////// pause 3 secs
VM230:22 [0.29334537521936, 0.08791952556930482, 0.02379906317219138, 0.9299911002162844, 0.4993608531076461]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment