Created
February 6, 2020 14:54
-
-
Save RichardMarks/76ea40073e7f6d9bd0f9c7cb5f6d5087 to your computer and use it in GitHub Desktop.
Promise catch order explained
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
// Promise catch order explained | |
// When catch() comes before then() in the promise chain, | |
// exceptions that occur in the then() handler will not be caught. | |
// If the promise rejects, the catch() handler will be called. | |
// If the catch() handler returns a value or a promise that resolves, | |
// the then() handler will be called. | |
mayThrowAnException() | |
.catch(handleError) | |
.then(handleResponse) | |
// is the same as | |
let response = null | |
try { | |
response = await mayThrowAnException() | |
} catch (err) { | |
handleError(err) | |
} | |
handleResponse(response) | |
// When catch() comes after then() in the promise chain, | |
// exceptions that occur in the then() handler will be caught. | |
// If the promise rejects, the then() handler will not be called, | |
// and the catch() handler will be called. | |
mayThrowAnException() | |
.then(handleResponse) | |
.catch(handleError) | |
// is the same as | |
try { | |
const response = await mayThrowAnException() | |
handleResponse(response) | |
} catch (err) { | |
handleError(err) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment