Skip to content

Instantly share code, notes, and snippets.

@rchaser53
Last active December 22, 2017 03:08
Show Gist options
  • Save rchaser53/7e63a93678821b03258bfd9b0dfe7da3 to your computer and use it in GitHub Desktop.
Save rchaser53/7e63a93678821b03258bfd9b0dfe7da3 to your computer and use it in GitHub Desktop.
async/await and return
async function waitAndMaybeReject() {
// Wait one second
await new Promise(r => setTimeout(r, 1000));
// Toss a coin
const isHeads = Boolean(Math.round(Math.random()));
if (isHeads) return 'yay'; // comment out when error
throw Error('Boo!');
}
async function foo() {
try {
waitAndMaybeReject();
}
catch (e) {
return 'caught';
}
}
/**
normal:
undefined 11
error:
(node:6359) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Boo!
(node:6359) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
*/
async function foo_await() {
try {
await waitAndMaybeReject();
}
catch (e) {
return 'caught';
}
}
/**
normal:
caught 11
error:
caught 11
*/
async function foo_return() {
try {
return waitAndMaybeReject();
}
catch (e) {
return 'caught';
}
}
/**
normal:
yay 11
error:
Error: Boo!
*/
async function foo_return_await() {
try {
return await waitAndMaybeReject();
}
catch (e) {
return 'caught';
}
}
/**
normal:
yay 11
error:
caught 11
*/
foo()
// foo_await()
// foo_return()
// foo_return_await()
.then((ret) => {
console.log(ret, 11)
})
.catch((err) => {
console.error(err)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment