Async & Await in JavaScript – Asynchronous programming is a fundamental part of JavaScript, especially in the context of web development where operations like fetching data from a server, reading files, or querying databases are common. JavaScript’s async and await keywords provide a way to write asynchronous code that is easy to read and maintain. In this article, we will dive deep into how async and await work, with coding examples to illustrate their usage.
What is Asynchronous Programming?
Async & Await in JavaScript – Asynchronous programming allows a program to do more than one thing at a time. This is particularly useful in web development to prevent blocking the main thread while waiting for network requests, file I/O, or other time-consuming operations.
Promises
Before async and await, JavaScript developers used Promises to handle asynchronous operations. A Promise is an object representing the eventual completion or failure of an asynchronous operation and its resulting value.
Example of Promise:
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Data received!');
}, 2000);
});
}
fetchData().then(response => {
console.log(response);
}).catch(error => {
console.error(error);
});
The async and await keywords in JavaScript make it easier to work with Promises. They allow you to write asynchronous code that looks and behaves like synchronous code.
async Keyword
The async keyword is used to declare an asynchronous function. An async function always returns a Promise.
async function fetchData() {
return 'Data received!';
}
fetchData().then(response => {
console.log(response);
});
Syntax for Async:
async function myFunction() {
return "Hello";
}
Example for async
const getData = async () => {
let data = "Hello World";
return data;
}
getData().then(data => console.log(data));
Output of the above code Async & Await in JavaScript – Understand the Mechanism:
Hello World
Explanation of the above code:
Here, an asynchronous function getData is declared using the arrow function syntax with the async keyword. Inside this function, a variable data is initialized with the string “Hello World”. Then, the function returns this data.
Syntax for Await
let value = await promise
an asynchronous function getData is declared using the arrow function syntax with the async keyword. Inside this function, a variable data is initialized with the string “Hello World”. Then, the function returns this data.
Async/Await Example
Here, we will be implementing several promises in a method, and then that method we will use for displaying our result. You can check the JS async/await syntax in the example.
function asynchronous_operational_method() {
let first_promise =
new Promise((resolve, reject) => resolve("Hello"));
let second_promise =
new Promise((resolve, reject) => {
setTimeout(() => {
resolve(" Codemagnet..");
}, 1000);
});
let combined_promise =
Promise.all([first_promise, second_promise]);
return combined_promise;
}
async function display() {
let data = await asynchronous_operational_method();
console.log(data);
}
display();
Output:
Hello Codemagnet
Explanation of the above code:
function asynchronous_operational_method() {
This line defines a function named asynchronous_operational_method. A function is like a recipe that tells the computer what steps to follow to accomplish a task.
let first_promise =
new Promise((resolve, reject) => resolve("Hello"));
Here, we’re creating a promise called first_promise. A promise is a way to handle asynchronous operations. Think of it as a “promise” that you will get a result (or an error) in the future. This promise immediately resolves with the value “Hello”.
let second_promise =
new Promise((resolve, reject) => {
setTimeout(() => {
resolve(" Codemagnet..");
}, 1000);
});
Next, we create another promise called second_promise. This one uses a setTimeout function, which means it will wait for 1 second (1000 milliseconds) before it resolves with the value ” Codemagnet..”.
let combined_promise =
Promise.all([first_promise, second_promise]);
Here, we use Promise.all to combine first_promise and second_promise into a single promise called combined_promise. Promise.all waits for all the included promises to resolve and then provides an array of their results.
return combined_promise;
Finally, this function returns the combined promise, which will resolve when both first_promise and second_promise have resolved.
async function display() {
This line defines another function named display. The async keyword indicates that this function will handle asynchronous operations using await.
let data = await asynchronous_operational_method();
Inside the display function, we use await to pause execution until the asynchronous_operational_method function completes and returns the combined promise’s result. The result is stored in the data variable.
console.log(data);
This line logs the data variable to the console. Since data is the result of asynchronous_operational_method, it will be an array containing the resolved values of the two promises: [“Hello”, ” Codemagnet..”].
display();
Finally, we call the display function, which starts the whole process.
await Keyword
The await keyword can only be used inside an async function. It makes JavaScript wait until the Promise is resolved or rejected.
async function fetchData() {
let promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("Data received!"), 2000);
});
let result = await promise; // Wait until the promise resolves
console.log(result); // "Data received!"
}
fetchData();
Let’s move on to some real time examples then you will understand easily how asyn and await works.
Consider a real-world example where we fetch data from an API using fetch, which returns a Promise.
So, how does it looks like Without async and await
function getData() {
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
}
getData();
But, when we use async and await
async function getData() {
try {
let response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
let data = await response.json();
console.log(data);
} catch (error) {
console.error('Error:', error);
}
}
getData();
Error Handling in Async & Await in JavaScript
Handling errors in asynchronous code can be tricky. With Promises, you use .catch(). With async and await, you use try and catch blocks to handle errors.
async function getData() {
try {
let response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
if (!response.ok) {
throw new Error('Network response was not ok');
}
let data = await response.json();
console.log(data);
} catch (error) {
console.error('Error:', error);
}
}
getData();
Parallel Execution with await
Sometimes you need to perform multiple asynchronous operations in parallel. await can be used in conjunction with Promise.all to wait for multiple promises to resolve.
async function fetchMultipleData() {
let urls = [
'https://jsonplaceholder.typicode.com/posts/1',
'https://jsonplaceholder.typicode.com/posts/2',
'https://jsonplaceholder.typicode.com/posts/3'
];
let promises = urls.map(url => fetch(url).then(response => response.json()));
try {
let results = await Promise.all(promises);
console.log(results);
} catch (error) {
console.error('Error:', error);
}
}
fetchMultipleData();
Conclusion
Using async and await in JavaScript can significantly improve the readability and maintainability of your asynchronous code. They help you write code that is more synchronous-like, making it easier to follow and debug. Remember, async functions always return a Promise, and you can use await to pause the execution of an async function until the Promise is resolved. By mastering these keywords, you can handle asynchronous operations more effectively and write cleaner, more efficient code.
Editor’s Note:
“Asynchronous code doesn’t have to be complicated. With async and await, you can write clear and concise asynchronous JavaScript.” – Anonymous





Leave a Reply