Spot the Unhandled Rejection
Question
This code has an unhandled promise rejection. What is wrong?
Code
async function load() {
const data = await fetch("/api/data");
return data.json();
}
load().then(data => console.log(data));
Hint
What happens if the fetch fails or the API returns an error?
Explanation
If fetch fails (network error) or data.json() throws (invalid JSON), the promise rejects but there is no .catch() handler — this causes an unhandled promise rejection. The fix is to add .catch(err => console.error(err)) after .then(), or wrap the await calls in a try/catch block inside the async function.
Related Resources
Related Lessons
- Async JavaScript
Learn about error handling with async/await.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.