Last active
February 2, 2016 15:43
-
-
Save mserranom/7552443b44e6feced9ab to your computer and use it in GitHub Desktop.
Different scenarios of ES6 promises and async/await catching and swallowing Errors
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
| "use strict"; | |
| function doThrow() { | |
| throw new Error("an error!"); | |
| } | |
| function doAsyncSuccess() : Promise<void> { | |
| return new Promise<void>((resolve, reject) => { | |
| setTimeout(() => resolve(), 10); | |
| }); | |
| } | |
| async function doAsyncFail() : Promise<void> { | |
| return new Promise<void>((resolve, reject) => { | |
| setTimeout(() => doThrow(), 10); | |
| }); | |
| } | |
| function doAsyncReject() : Promise<void> { | |
| return new Promise<void>((resolve, reject) => { | |
| setTimeout(() => reject('promise rejected'), 10); | |
| }); | |
| } | |
| async function run() { | |
| await doAsyncSuccess(); | |
| await doAsyncFail(); | |
| } | |
| async function runAndThrow() { | |
| await doAsyncSuccess(); | |
| throw new Error("a sync error in async function!"); | |
| } | |
| async function runAndReject() { | |
| await doAsyncSucces(); | |
| await doAsyncReject(); | |
| } | |
| doAsyncSuccess().then(()=> doAsyncFail()); | |
| // throw new Error("an error!"); | |
| // ^ | |
| // | |
| // Error: an error! | |
| doAsyncSuccess().then(()=> {throw new Error('error thrown in .then()')}); | |
| // NO OUTPUT | |
| run(); | |
| // throw new Error("an error!"); | |
| // ^ | |
| // | |
| // Error: an error! | |
| runAndThrow(); | |
| // NO OUTPUT | |
| run().catch(reason => console.log('caught error: ' + reason)); | |
| // throw new Error("an error!"); | |
| // ^ | |
| // | |
| // Error: an error! | |
| runAndThrow().catch(reason => console.log('caught error: ' + reason)); | |
| // caught error: Error: a sync error in async function! | |
| runAndReject(); | |
| // NO OUTPUT | |
| runAndReject().catch(reason => console.log('caught error: ' + reason)); | |
| // caught error: promise rejected |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment