Node.jsQuestion 07 of 26
Handling asynchrony
Answer out loud or in your head first, then compare.
Answer
The basic tools are callbacks, Promises and async/await. Events and streams, in turn, suit a series of results, e.g. data arriving over a connection.
JavaScript
async function load() {
try {
const response = await fetch('https://example.com/api/items');
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return await response.json();
} catch (error) {
console.error('Failed to fetch data', error);
throw error;
}
}Pitfall: fetch doesn't reject its Promise just because the server returned HTTP 404 or 500. You have to check the status. For real requests I also plan a timeout and cancellation.
How did it go? Be honest — “Not yet” puts the question on your review list.