Skip to content

Instantly share code, notes, and snippets.

@munkacsitomi
Last active March 1, 2020 15:46
Show Gist options
  • Save munkacsitomi/8f0ac55b3bbbbb448b803d072d9fbbfa to your computer and use it in GitHub Desktop.
Save munkacsitomi/8f0ac55b3bbbbb448b803d072d9fbbfa to your computer and use it in GitHub Desktop.
Async/Await error handling
const fetchAndUpdatePosts = () => {
fetchPosts()
.then((posts) => {
updatePosts(posts)
.catch((err) => {
console.log('error in updating posts');
});
})
.catch(() => {
console.log('error in fetching posts');
});
}
const fetchAndUpdatePosts = async () => {
let posts;
try {
posts = await fetchPosts();
} catch {
console.log('error in fetching posts');
}
if (!posts) {
return;
}
try {
await updatePosts();
} catch {
console.log('error in updating posts');
}
}
const fetchAndUpdatePosts = async () => {
let posts;
try {
posts = await fetchPosts();
doSomethingWithPosts(posts); // throws an error
} catch {
// Now it handles errors from fetchPosts and doSomthingWithPosts.
console.log('error in fetching posts');
}
}
const fetchAndUpdatePosts = async () => {
const posts = await fetchPosts().catch(() => {
console.log('error in fetching posts');
});
if (posts) {
doSomethingWithPosts(posts);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment