Skip to content

Instantly share code, notes, and snippets.

@tsmx
Last active November 11, 2020 20:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tsmx/b7e75f327ddcfcb2b83d0753a457b0aa to your computer and use it in GitHub Desktop.
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.
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