Skip to content

Instantly share code, notes, and snippets.

@maoueh
Last active August 29, 2019 07:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maoueh/5a610f4f404b13ec835db911de135fe6 to your computer and use it in GitHub Desktop.
Save maoueh/5a610f4f404b13ec835db911de135fe6 to your computer and use it in GitHub Desktop.
A quick script to play with Promise nesting and resolution (node index.js)
function buildPromise(tag, shouldError) {
if (shouldError) {
return new Promise((resolve, reject) => {
console.log(tag + " executor")
setTimeout(() => { console.log(tag + " rejecting!"); reject(tag + " failed on purpose") }, 250)
})
}
return new Promise((resolve, reject) => {
console.log(tag + " executor")
setTimeout(() => { console.log(tag + " resolving!"); resolve(tag + " succeed on purpose") }, 250)
})
}
// Play with the `false/true` values are different places which controls resolve/reject for each promise
// Play with then/catch structure and nesting to see how the various things connects together
buildPromise("top", false).then((result) => {
console.log(result + " => then block")
return Promise.all([buildPromise("then > child1", false), buildPromise("then > child2", true), buildPromise("then > child1", false)])
}).catch((error) => {
console.log(error + " => catch block")
return Promise.all([buildPromise("catch > child1", false), buildPromise("catch > child2", false), buildPromise("catch > child1", false)])
}).then((result) => {
console.log("after top", result)
})
$ node /tmp/promise-test.js
top executor
top resolving!
top succeed on purpose => then block
then > child1 executor
then > child2 executor
then > child1 executor
then > child1 resolving!
then > child2 rejecting!
then > child1 resolving!
then > child2 failed on purpose => catch block
catch > child1 executor
catch > child2 executor
catch > child1 executor
catch > child1 resolving!
catch > child2 resolving!
catch > child1 resolving!
after top [ 'catch > child1 succeed on purpose',
'catch > child2 succeed on purpose',
'catch > child1 succeed on purpose' ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment