Skip to content

Instantly share code, notes, and snippets.

@fractalf
Created June 10, 2016 12:15
Show Gist options
  • Save fractalf/c0eb369373d8fb1242ebb537e20e4794 to your computer and use it in GitHub Desktop.
Save fractalf/c0eb369373d8fb1242ebb537e20e4794 to your computer and use it in GitHub Desktop.
Javascript: Recursive functions and Promises/A+
/**
* 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