JavaScript
Async/Await Syntax
Simplify Promises
Understanding Async/Await in JavaScript
In JavaScript, asynchronous programming allows you to perform long network requests or operations without blocking the main thread. async/await was introduced in ES2017 (ES8) and is built on top of Promises to make asynchronous code easier to read and write.
What is async?
An async function is a function that always returns a Promise. Inside it, you can use the await keyword to pause execution until a Promise resolves.
What is await?
The await keyword can only be used inside an async function. It waits for the Promise to resolve and returns the result. If the Promise is rejected, it throws the error.
Basic Example of Async/Await
Let’s simulate a network request using setTimeout wrapped in a Promise, then use async/await to call it.
function fetchData() {
return new Promise((resolve) => {
setTimeout(() => {
resolve("Data received!");
}, 2000);
});
}
async function displayData() {
console.log("Fetching...");
const result = await fetchData();
console.log(result);
}
displayData();
Fetching... Data received!
Why use async/await over Promises?
While Promises work fine, they can lead to nested .then() chains, which are harder to read and maintain. async/await flattens this structure, making your code easier to follow.
Chaining Multiple Await Calls
You can chain multiple await calls sequentially just like synchronous code:
function delay(message, ms) {
return new Promise((resolve) => {
setTimeout(() => resolve(message), ms);
});
}
async function chainMessages() {
const msg1 = await delay("Step 1 complete", 1000);
console.log(msg1);
const msg2 = await delay("Step 2 complete", 1000);
console.log(msg2);
const msg3 = await delay("Step 3 complete", 1000);
console.log(msg3);
}
chainMessages();
Step 1 complete Step 2 complete Step 3 complete
What happens if a Promise fails?
If a Promise rejects, the await line throws an error. You must handle it using try...catch blocks inside async functions.
Using try/catch with Async/Await
function fetchUser() {
return new Promise((_, reject) => {
setTimeout(() => reject("User not found"), 1000);
});
}
async function getUserData() {
try {
const user = await fetchUser();
console.log(user);
} catch (error) {
console.error("Error:", error);
}
}
getUserData();
Error: User not found
Q: Can we use await outside of async function?
A: No, await can only be used inside an async function. Using it outside will result in a syntax error (except in top-level code in modern environments like recent versions of Node.js or browsers).
Summary
asyncfunctions return Promises.awaitpauses the execution of the function until the Promise resolves.- Use
try/catchto handle errors gracefully. - Async/await makes asynchronous code look and behave more like synchronous code.
Next Topic ⮕Fetch API in JavaScript - Get & Post Data
Comments
Loading comments...