Last active
August 29, 2019 07:38
-
-
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)
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
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) | |
}) |
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
$ 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