Async/await makes working with Promises easier and helps us write asynchronous code in a clean, readable way.
Let's understand it with simple examples!
1. What Is Async/Await?
async and await are JavaScript keywords used to work with asynchronous operations.
-
asyncis used to declare an asynchronous function. -
awaitwaits for a Promise to settle before continuing the execution of that async function.
2. Understanding async
When we use async before a function, that function always returns a Promise.
async function greet() {
return "Hello, JavaScript!";
}
greet().then((message) => {
console.log(message);
});
Output:
Hello, JavaScript!
Even though we return a normal string, the async function returns a Promise that fulfills with that string.
3. Understanding await
The await keyword waits for a Promise's result before continuing inside the async function.
function getData() {
return new Promise((resolve) => {
setTimeout(() => {
resolve("Data received!");
}, 2000);
});
}
async function displayData() {
const result = await getData();
console.log(result);
}
displayData();
Output after approximately two seconds:
Data received!
Here, await waits for the Promise returned by getData() to fulfill before assigning its value to result.
Note: await pauses the async function, not the entire JavaScript application.
4. Using Async/Await with Fetch API
We often use async/await when fetching data from an API.
async function getProducts() {
const response = await fetch(
"https://fakestoreapi.com/products"
);
const products = await response.json();
console.log(products);
}
getProducts();
Let's understand the code:
-
fetch()requests product data from the API. -
awaitwaits for the response. -
response.json()reads and parses the response body. -
awaitwaits for the parsed data. -
console.log()displays the products.
5. Handling Errors with Try/Catch
Sometimes, an API request may fail. We can use try...catch to handle errors.
async function getProducts() {
try {
const response = await fetch(
"https://fakestoreapi.com/products"
);
if (!response.ok) {
throw new Error("Failed to fetch products");
}
const products = await response.json();
console.log(products);
} catch (error) {
console.log("Error:", error.message);
}
}
getProducts();
The try block contains the code we want to execute. If an error is thrown or an awaited Promise rejects, the catch block handles it.
Checking response.ok is important because fetch() does not automatically throw an error for HTTP responses such as 404 Not Found.
6. Async/Await vs. Then/Catch
Both approaches can handle Promises.
Using .then():
fetch("https://fakestoreapi.com/products")
.then((response) => response.json())
.then((products) => console.log(products))
.catch((error) => console.log(error));
Using async/await:
async function getProducts() {
try {
const response = await fetch(
"https://fakestoreapi.com/products"
);
const products = await response.json();
console.log(products);
} catch (error) {
console.log(error);
}
}
getProducts();
Both approaches work with Promises. Many developers prefer async/await because it can make asynchronous code easier to read.
Conclusion
Async/await is an important JavaScript concept, especially when working with APIs and modern frameworks like React.
Remember:
-
asyncmakes a function return a Promise. -
awaitwaits for a Promise's result inside an async function. -
try...catchhelps handle errors. - Async/await makes asynchronous code easier to read.
Keep practising these examples to improve your JavaScript skills.
Happy Coding! 🚀
Top comments (0)