Skip to content

Instantly share code, notes, and snippets.

@jguix
Last active December 10, 2022 16:22
Show Gist options
  • Save jguix/0618717288fae0c12a4fd9bfd7d17fe2 to your computer and use it in GitHub Desktop.
Save jguix/0618717288fae0c12a4fd9bfd7d17fe2 to your computer and use it in GitHub Desktop.
How to create a recursive promise chain. Source http://jsbin.com/qotabib/edit?js,console
// A recursive function returning Promise<number>
function recurseToZero(n) {
console.log('B. Entering recursive function for [' + n + '].');
// Once we hit zero, bail out of the recursion. The key to recursion is that
// it stops at some point, and the callstack can be "rolled" back up.
if (n === 0) {
// We could just return 0 but we do return Promise.resolve to have a consistent return type
return Promise.resolve(0);
}
// Start a NEW PROMISE CHAIN that will become the continuation of the parent
// promise chain. This new promise chain now becomes a completely tangential
// branch to the parent promise chain.
return new Promise((resolve) => {
setTimeout(() => {
resolve(recurseToZero(n-1));
}, 500);
});
}
Promise.resolve()
.then(() => {
console.group("A. Recursion starts.");
return(3);
})
.then(n => {
// With the recursive function we are creating a totally
// TANGENTIAL BRANCH of the Promise chain.
// --
// A
// |
// B --> B'3 --> B'2 --> B'1 --> B'0
// |
// C
return recurseToZero(n);
})
.then(() => {
console.groupEnd("C. Recursion ended.");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment