Promises & Async/Await

Duration: 20 min  •  Difficulty: Hard

JavaScript in the browser lives in a "single-threaded" architecture. If it gets stuck waiting for an API to finish fetching data, the entire Website UI cannot be scrolled or clicked.

To overcome this, the concept of Async was introduced, where it throws the data fetching process to the browser's back-door and promises (Promise) to notify when the data is ready.

Async / Await

The modern style for catching a *Promise* without nested callback techniques inside .then() (which can create "Callback Hell") is called the *Async/Await* syntax combination.

main.js
// 1. Assert that this is an Async Function
const fetchUserData = async () => {
try {
// 2. Await: Don't move to the line below before this promise is fulfilled (fetching API)
const response = await fetch("https://jsonplaceholder.typicode.com/users/1");
// 3. Await unpacking the response body into pure JSON
const user = await response.json();
console.log(`User Data Successfully Reached: ${user.name}`);
} catch (error) {
console.error("Failed to fetch data:", error);
}
}
fetchUserData();