Created
December 21, 2015 03:53
-
-
Save melissamarima/ee9defc4cf2f8b10ad0b to your computer and use it in GitHub Desktop.
Understanding fat arrows
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
//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