Last active
March 1, 2020 15:46
-
-
Save munkacsitomi/8f0ac55b3bbbbb448b803d072d9fbbfa to your computer and use it in GitHub Desktop.
Async/Await error handling
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
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