Async, Await, Try Catch JS (Promises)
-
-
Save NdagiStanley/9fefd08f366f5affb14339bf4c97726b to your computer and use it in GitHub Desktop.
JS | Promises
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
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, | |
// ... | |
// }, | |
// {..} | |
// ... | |
// ] |
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
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 |
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
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")); | |
// |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Target: Novice in JS
Source: https://itnext.io/error-handling-with-async-await-in-js-26c3f20bc06a
Opinion: Use
Solution 1
since it's clear.