There are no items in your cart
Add More
Add More
Item Details | Price |
---|
• Yash Gupta • Feb 19, 2025 • 8 mins read
Async/Await is simply syntactic sugar that makes working with promises more convenient and readable. It provides a simpler and more intuitive way to handle asynchronous operations compared to traditional Promises.
Async/Await attempts to solve one of the biggest pains in the language since its beginning that is synchrony.
They let you write promise-based code in a synchronous style without blocking the main thread, making your asynchronous code cleaner and more readable.
Before I start with Async/Await, I suggest you look at my article on Promises in JavaScript to understand them. You need to understand Promises before you can understand how to use Async/Await.
const asyncFunc = async () => {// to handle errors in async/await we use try and catch blocktry {// we will store only resolved value in resolvedValue variableconst resolvedValue = await promise;}catch (rejectedValue) {// handle only rejected value (error) here}}
What are we doing?
// Let's assume that this `products` variable is a data that is// already present in our databaseconst products = [{title: "Speaker",price: "7999",},{title: "Laptop",price: "75999",},{title: "Headphones",price: "5999",},];const createProduct = (product) => {return new Promise((resolve, reject) => {// here setTimeout is immitating time require to fetch data/api from serversetTimeout(() => {// lets say there is no errorlet error;if (product) {// if we receive a product that means there is no errorerror = false;// so we will push the received product in our existing products' arrayproducts.push(product);} else {// if we don't receive a product that means there is some errorerror = true;}if (!error) {resolve("Created the product successfully");} else {reject("Some error occurred");}}, 3000);});};let fetchProducts = () => {console.log("fetching the products...\n");// here setTimeout is immitating time require to fetch data/api from serversetTimeout(() => {products.forEach((prod) => {console.log(prod.title);});}, 2000);};// async functionconst asynFunc = async () => {// try and catch for error handelingtry {// we will store the 'resolved' value in productsMsglet productsMsg = await createProduct({title: "new product",price: "399",});console.log(productsMsg);fetchProducts();} catch (error) {// we will get 'rejected' value as an errorconsole.log(error);}};asynFunc();console.log("next lines of code\n");
When we call asyncFunc() which is an async function, it will wait until createProduct() promise returns a resolved or rejected value (Depending on the value of the error variable).
If the promise is resolved then only it will fetch the products by executing fetchProducts(), otherwise, it will throw an error by rejecting the promise
Say we wanted to fetch a URL and console log the response. Here's how it looks using Promises:
const fetchUrl = (url) => {return axios.get(url).then((response) => {console.log(response.data);}).catch((err) => {// Handle Error Hereconsole.error(err);});};
And here's the same thing using async/await functions:
const fetchUrl = async (url) => {try {const response = await axios.get(url);console.log(response.data);} catch (err) {// Handle Error Hereconsole.error(err);}};
If you notice, unlike promises in the async/await function, all the callbacks are gone. This makes it easier to read, especially for those who are not familiar with promises.
I hope this post will help you in your journey. Keep learning!
Yash Gupta
I am passionate about tech and coding. I share expert insights on Test Automation (Selenium, Cypress, Playwright), API Automation, JavaScript, Python, Svelte, Vue.js, ReactJS, Angular, Flutter, and more. Stay updated with the latest trends! 🚀