JavaScript Async/Await & Fetch API
Master modern asynchronous JavaScript. Learn how to fetch data from APIs without blocking the main thread using async/await.
Asynchronous JavaScript
JavaScript is single-threaded. This means it can only do one thing at a time. However, fetching data from a network takes time. Asynchronous operations allow JS to execute other tasks while waiting for network requests to finish.
The Fetch API
The Fetch API provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline, such as requests and responses.
Async and Await
The async and await keywords (introduced in ES8) enable asynchronous, promise-based behavior to be written in a cleaner style, avoiding promise chains.
async function getUserData() {
try {
// Await pauses execution until the promise settles
const response = await fetch('https://jsonplaceholder.typicode.com/users/1');
if (!response.ok) {
throw new Error('Network response was not ok');
}
// Parsing the JSON body
const data = await response.json();
console.log(data.name);
} catch (error) {
// Error handling
console.error('Fetch error:', error);
}
}Important: You can only use the await keyword inside a function declared with async.