Last active
November 11, 2020 20:10
-
-
Save tsmx/b7e75f327ddcfcb2b83d0753a457b0aa to your computer and use it in GitHub Desktop.
NodeJS Promise example showing basic usage and control flow with: resolve, reject, then, catch & throw.
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
function isOdd(x) { | |
return new Promise((resolve, reject) => { | |
if (x == 11) throw new Error('11 is not allowed!'); | |
if (x % 2) { | |
resolve(x.toString() + ' is odd') | |
} | |
else { | |
reject(new Error(x.toString() + ' is even')); | |
} | |
}); | |
} | |
function testIsOdd(x) { | |
isOdd(x) | |
.then((result) => { console.log('then:', result); }) | |
.catch((error) => { console.log('catch:', error.message); }); | |
} | |
testIsOdd(9); | |
testIsOdd(10); | |
testIsOdd(11); | |
// output | |
// then: 9 is odd | |
// catch: 10 is even | |
// catch: 11 is not allowed! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment