Async and Await in JavaScript
The async and await keywords make Promise-based asynchronous JavaScript easier to write, read, and understand.
What are async and await?
JavaScript uses asynchronous programming to perform time-consuming tasks without blocking the application. Promises represent the result of an asynchronous operation, while async and await provide a cleaner way to work with those Promises.
Simple Definition
async is used to declare an asynchronous function.
await pauses the execution of an async function until a Promise is completed.
Together, async and await make asynchronous code look more like normal step-by-step code.
async vs await
async
The async keyword is placed before a function. An async function returns a Promise.
await
The await keyword is used inside an async function to wait for a Promise to complete.
Example 1: async Function
An async function automatically returns a Promise.
async function getMessage() {
return "Hello from async function";
}
getMessage().then(function(result) {
console.log(result);
});
Example 2: await with Promise
The await keyword waits for a Promise to complete before continuing with the next statement.
function getData() {
return Promise.resolve("Data received");
}
async function loadData() {
const result = await getData();
console.log(result);
}
loadData();
Example 3: async/await with try-catch
async and await can also be used with try-catch for error handling.
function getData() {
return Promise.resolve("Data loaded successfully");
}
async function loadData() {
try {
const result = await getData();
console.log(result);
}
catch (error) {
console.log("Error:", error);
}
}
loadData();
Why Use async and await?
Important Benefits
• Makes asynchronous code easier to read.
• Reduces complicated Promise chains.
• Makes asynchronous operations look sequential.
• Works naturally with try-catch error handling.
• Useful for API and network operations.
Example 🌍🤓
In a real application, async and await are commonly used when retrieving data from an API.
Summary
The async keyword is used to create an asynchronous function, while await is used to wait for a Promise inside that function. Together they make asynchronous JavaScript easier to read and maintain. They are commonly used with Promises, API requests, and error handling with try-catch.