Skip to content

Instantly share code, notes, and snippets.

@NdagiStanley
Last active April 2, 2022 06:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NdagiStanley/9fefd08f366f5affb14339bf4c97726b to your computer and use it in GitHub Desktop.
Save NdagiStanley/9fefd08f366f5affb14339bf4c97726b to your computer and use it in GitHub Desktop.
JS | Promises

JavaScript

Async, Await, Try Catch JS (Promises)

AsyncAwaitTryCatch

Handling UnhandledPromiseRejectionWarning

Stacktrace:

This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch().
const fetch = require("node-fetch");
async function fetchUsers() {
const res = await fetch("https://jsonplaceholder.typicode.com/users");
const data = await res.json();
console.log(res.json());
}
fetchUsers();
// Output
// [
// {
// id: 1,
// ...
// },
// {..}
// ...
// ]
function thisThrows() {
throw new Error("Thrown by thisThrows()");
}
try {
thisThrows();
} catch (error) {
console.error(error);
} finally {
console.log("We do clean up here");
}
// Output:
// Error: Thrown from thisThrows()
// ...stacktrace
// We do clean up here
async function thisPromiseThrows() {
throw new Error("Thrown by thisPromiseThrows()");
}
try {
thisPromiseThrows();
} catch (error) {
console.error(error);
} finally {
console.log("We do clean up here");
}
// Output: // Notice the mixed up order of the output plus the UnhandledPromiseRejectionWarning
// We do clean up here
// UnhandledPromiseRejectionWarning: Error: Thrown from thisPromiseThrows()
// Solution 1
async function thisPromiseThrows() {
throw new Error("Thrown by thisPromiseThrows()");
}
async function run() {
try {
await thisPromiseThrows(); // <- Notice the await keyword here
} catch (error) {
console.error(error);
} finally {
console.log("We do clean up here");
}
};
run();
// Solution 2
async function thisPromiseThrows() {
throw new Error("Thrown by thisPromiseThrows()");
}
thisPromiseThrows()
.catch(console.error)
.then(() => console.log("We do clean up here"));
//
@NdagiStanley
Copy link
Author

Target: Novice in JS

Source: https://itnext.io/error-handling-with-async-await-in-js-26c3f20bc06a

Opinion: Use Solution 1 since it's clear.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment