Created
June 10, 2016 12:15
-
-
Save fractalf/c0eb369373d8fb1242ebb537e20e4794 to your computer and use it in GitHub Desktop.
Javascript: Recursive functions and Promises/A+
This file contains 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
/** | |
* Javascript Promises/A+ and recursive functions | |
* A simplified example | |
* Inspired by: https://kostasbariotis.com/node-js-recursion/ | |
* | |
* Output: | |
* 1: async job simulation started | |
* 1: job done | |
* 2: async job simulation started | |
* 2: job done | |
* 3: async job simulation started | |
* 3: job done | |
* all done! | |
*/ | |
rec(1) | |
.then((res) => { | |
console.log(res); | |
}); | |
function rec(depth) { | |
return new Promise((fulfill, reject) => { | |
console.log(depth + ': async job simulation started'); | |
setTimeout(() => { | |
console.log(depth + ': job done'); | |
fulfill(depth); | |
}, 1000); | |
}) | |
.then((depth) => { | |
if (depth < 3) { | |
return rec(depth + 1); | |
} else { | |
return "all done!"; | |
} | |
}) | |
.catch((err) => { | |
console.log(err); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment