Async/Await in JavaScript: Writing Cleaner Asynchronous Code
<p>“If you write asynchronous code using promises, this blog is for you.<br> In this blog, we explore Async/Await in JavaScript.”</p> <p>What is Async/Await:</p> <p>Async/Await keywords are used to write asynchronous code that looks like synchronous code. It makes your code more readable and clean.<br> They are just syntactic sugar over JavaScript promises.</p> <p>Async keyword:</p> <p>We can use the async keyword with any function. This keyword ensures that the function always returns a promise.<br> If a function returns a non-promise value, JavaScript automatically wraps it in a resolved promise.</p> <p>Await keyword:</p> <p>We use the await keyword with code that takes time to resolve.<br> The await keyword pauses the execution of the function until the promise is either resolved or rej
“If you write asynchronous code using promises, this blog is for you. In this blog, we explore Async/Await in JavaScript.”
What is Async/Await:
Async/Await keywords are used to write asynchronous code that looks like synchronous code. It makes your code more readable and clean. They are just syntactic sugar over JavaScript promises.
Async keyword:
We can use the async keyword with any function. This keyword ensures that the function always returns a promise. If a function returns a non-promise value, JavaScript automatically wraps it in a resolved promise.
Await keyword:
We use the await keyword with code that takes time to resolve. The await keyword pauses the execution of the function until the promise is either resolved or rejected. While the function is paused, the JavaScript thread is free to perform other tasks.
How Async/Await work together: async creates a promise based function. await wait for the promise to resolve inside that function.
Code Example of Async/Await
function fetchData() { return new Promise((resolve, reject) => { setTimeout(() => { resolve("Data fetched successfully!"); }, 2000); }); }function fetchData() { return new Promise((resolve, reject) => { setTimeout(() => { resolve("Data fetched successfully!"); }, 2000); }); }// async function async function getData() { console.log("Fetching data...");
const result = await fetchData(); // waits here
console.log(result); }
getData();`
Enter fullscreen mode
Exit fullscreen mode
output : Fetching data... (Data comes after 2 seconds) Data fetched successfully!output : Fetching data... (Data comes after 2 seconds) Data fetched successfully!Enter fullscreen mode
Exit fullscreen mode
Same code Without Async/Await(Promises)
function fetchData() { return new Promise((resolve, reject) => { setTimeout(() => { resolve("Data fetched successfully!"); }, 2000); }); }function fetchData() { return new Promise((resolve, reject) => { setTimeout(() => { resolve("Data fetched successfully!"); }, 2000); }); }function getData() { console.log("Fetching data...");
fetchData().then((result) => { console.log(result); }); }
getData();`
Enter fullscreen mode
Exit fullscreen mode
.then() callback style. await easy to read and understand.
Error handling with async code :
Error handling in asynchronous code ensures that failures (like database errors) are handled without crashing the application.
Try-Catch is the standard way to handle errors in modern JavaScript. You use the await keyword inside the try block. If any error occurs, the catch block executes and handles the error.
async function getData() { try { const result = await fetchData(); // if promise rejects, control goes to catch console.log(result); } catch (error) { console.log("Error:", error); } }async function getData() { try { const result = await fetchData(); // if promise rejects, control goes to catch console.log(result); } catch (error) { console.log("Error:", error); } }Enter fullscreen mode
Exit fullscreen mode
Conclusion :
In this blog, we learned how to write cleaner and more readable asynchronous code using the Async/Await keywords. We also explored error handling using try-catch inside an asynchronous function.
DEV Community
https://dev.to/abhishek_sahni_c83807f8fe/asyncawait-in-javascript-writing-cleaner-asynchronous-code-2k4iSign in to highlight and annotate this article

Conversation starters
Daily AI Digest
Get the top 5 AI stories delivered to your inbox every morning.
More about
application
Some things I noticed while LARPing as a grantmaker
Written to a new grantmaker. The first three points are the most important. Focus on opportunities many times your bar. Most value comes from finding/creating projects many times your bar, rather than discriminating between opportunities around your bar. If you find/create a new opportunity to donate $1M at 10x your bar (and cause it to get $1M, which would otherwise be donated to a 1x thing), you generate $9M of value (at your bar). [1] If you cause a $1M at 1.5x opportunity to get funded or a $1M at 0.5x opportunity to not get funded, you generate $500K of value. The former is 18 times as good. You should probably be like I do research to figure out what projects should exist, then make them exist rather than I evaluate the applications that come to me . That said, most great ideas come

This bike rack pioneer is selling Bluetooth suction cups to stick bikes to your car
Richard Allen didn't invent the automobile bike rack - his 1967 patent application makes it clear that others came before. But after nearly sixty years selling popular and simple mechanical bike carriers, his company Allen Bikes now offers a line of - yes - Bluetooth-monitored suction cups to stick bikes to your car. If you [ ]

Data centres: Building opportunities on solid foundations
Data centres power New Zealand’s digital economy, enabling cloud , AI and critical services. With billions in investment ahead, collaboration and sustainable infrastructure are key to long-term growth. The backbone of our digital economy Every business-critical system – from banking platforms to supply chains, financial transactions to enterprise applications – relies on data centres. Data centres are the unseen engine rooms: powering cloud platforms, processing expanding AI workloads and underpinning critical services across every industry. The recent NZTech report, Empowering Aotearoa New Zealand’s Digital Future – Our National Data Centre Infrastructure , highlighted the scale of the opportunity for our data centre sector. With 56 operational data centres (four of which are owned and op
Knowledge Map
Connected Articles — Knowledge Graph
This article is connected to other articles through shared AI topics and tags.
More in Products

Why Australia’s tech sovereignty needs smart partnerships
Geopolitical risk, cyber threats and outages are driving a rethink of how we build, run and protect the infrastructure powering the economy, argues Mark Hile, Datacom MD, Infrastructure Products. As someone entrusted with overseeing infrastructure products for a company that acts as a tech partner to hundreds of Australian organisations, both enterprise and government, the conversation around digital resilience , sovereignty and strengthening local infrastructure and networks has never felt more urgent – or more personal. After more than a decade working closely with Datacom’s customers, I believe our sector stands at an inflection point. We must either double down on building trusted, regionally-owned technology infrastructure or risk losing strategic control to offshore interests and unc

Reddit is moving on from r/all
Reddit is deprecating r/all, one of its feeds that shows popular posts on the platform, as part of "ongoing efforts to simplify Reddit and improve Home feed personalization." Reddit has offered both r/popular and r/all as ways to see trending posts, with r/all being a "less filtered feed" where "sexually explicit posts are filtered out [ ]




Discussion
Sign in to join the discussion
No comments yet — be the first to share your thoughts!