Skip to main content
Advertisement

JavaScript: Asynchronous Processing (Async/Await)

1. What is Asynchronous Programming?

JavaScript is a single-threaded language, meaning it can only process one task at a time. However, to prevent the main thread from freezing while waiting for long-running tasks like network requests or timers, Asynchronous processing is essential.


2. Promise

A Promise is an object representing the eventual completion (or failure) of an asynchronous operation and its resulting value.

const fetchData = new Promise((resolve, reject) => {
setTimeout(() => {
const success = true;
if (success) {
resolve("Data fetched successfully!");
} else {
reject("Data load failed.");
}
}, 2000);
});

fetchData
.then((data) => console.log(data))
.catch((err) => console.error(err));

3. Async / Await

Introduced in ES2017 (ES8), the async/await syntax allows you to write asynchronous code that reads like synchronous code, making it easier to follow.

Basic Usage

async function getUserData() {
try {
const response = await fetch('https://api.example.com/user');
const user = await response.json();
console.log(user);
} catch (error) {
console.error("Error occurred while fetching user data:", error);
}
}

4. Pro Tip: Promise.all

Useful for processing multiple asynchronous operations in parallel.

async function fetchMultiple() {
const [res1, res2] = await Promise.all([
fetch('/api/data1'),
fetch('/api/data2')
]);
// Waits until both requests are completed
}
Advertisement