Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@melissamarima
Created December 21, 2015 03:53
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/ee9defc4cf2f8b10ad0b to your computer and use it in GitHub Desktop.
Save melissamarima/ee9defc4cf2f8b10ad0b 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)
})
/*
BAM! Everything output at once! NO TIMEOUT PAUSES AT ALL
VM224:13 in loop
VM224:5 in asyncFunc
VM224:13 in loop
VM224:5 in asyncFunc
VM224:13 in loop
VM224:5 in asyncFunc
VM224:13 in loop
VM224:5 in asyncFunc
VM224:13 in loop
VM224:5 in asyncFunc
VM224:22 [0.6260232019703835, 0.3711804535705596, 0.36812554858624935, 0.2748239105567336, 0.9398391374852508]
VM224:7 out asyncFunc
VM224:7 out asyncFunc
VM224:7 out asyncFunc
VM224:7 out asyncFunc
VM224:7 out asyncFunc
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment