-
-
Save martin-mok/1d13a385caa057bb779ae502ad4a8535 to your computer and use it in GitHub Desktop.
How to create a recursive promise chain. Source http://jsbin.com/qotabib/edit?js,console
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
// 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