⬅ Previous Topic
JavaScript Promises - Creating and ChainingNext Topic ⮕
Fetch API in JavaScript - Get & Post Data⬅ Previous Topic
JavaScript Promises - Creating and ChainingNext Topic ⮕
Fetch API in JavaScript - Get & Post DataIn 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.
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.
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.
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!
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.
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
If a Promise rejects, the await
line throws an error. You must handle it using try...catch
blocks inside async functions.
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
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).
async
functions return Promises.await
pauses the execution of the function until the Promise resolves.try/catch
to handle errors gracefully.⬅ Previous Topic
JavaScript Promises - Creating and ChainingNext Topic ⮕
Fetch API in JavaScript - Get & Post DataYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.