- Courses
- đ»Programming Languages
- đJavaScript
- Asynchronous JavaScript
- Async/Await
On this page
Async/Await: Writing Asynchronous Code That Looks Synchronous
By Enrico Hochkoeppler
Web Developer & TutoriaLibre Founder
As applications scale, managing long chains of .then() and .catch() can become mentally taxing and visually cluttered. Introduced in ES2017, Async/Await is a syntactic sugar built on top of Promises. It does not change how JavaScript handles asynchronicity under the hood; instead, it provides a cleaner way to write and read asynchronous logic, making it appear as if it were a standard sequential script.
The Async Keywordâ
To use this modern syntax, you must first prefix a function declaration with the async keyword. This modification has two primary effects:
- Guaranteed Promise: An
asyncfunction always returns a Promise. If the function returns a value that is not a Promise, JavaScript automatically wraps that value in a resolved Promise. - Enables Await: It unlocks the use of the
awaitkeyword inside that functionâs body.
async function greet() {
return "Hello, Student";
}
// Equivalent to:
// function greet() { return Promise.resolve("Hello, Student"); }
greet().then((message) => console.log(message));
The Await Keywordâ
The await keyword can only be used inside an async function. When placed before a Promise, it tells the JavaScript engine to pause the execution of that specific function until the Promise settles (either resolves or rejects).
While the function execution is paused, the main thread is not blocked. The Event Loop continues to handle other tasks, such as user interactions or animations, maintaining the applicationâs responsiveness.
async function getSystemData() {
console.log("Request started...");
// Execution pauses here until the Promise resolves
const data = await fetchDatabaseRecord();
console.log("Data received:", data);
console.log("Request finished.");
}
Without await, data would be a pending Promise object. With await, data becomes the actual resolved value.
Sequential vs. Parallel Executionâ
One of the most common pitfalls for beginners is inadvertently slowing down their applications by awaiting tasks that do not depend on each other.
Sequential Execution (Slow)â
In this example, task2 will not even begin until task1 has completely finished.
async function loadContent() {
const user = await fetchUser(); // Takes 2 seconds
const posts = await fetchPosts(); // Takes 2 seconds
// Total time: 4 seconds
}
Parallel Execution (Fast)â
If the tasks are independent, you should initiate them simultaneously and then await the results collectively using Promise.all().
async function loadContentFast() {
const userPromise = fetchUser();
const postsPromise = fetchPosts();
// Both requests are running at the same time
const [user, posts] = await Promise.all([userPromise, postsPromise]);
// Total time: 2 seconds
}
Error Handling with Try/Catchâ
In the previous lesson, we used .catch() to handle Promise rejections. With async/await, we return to the traditional try...catch block. This is highly beneficial as it allows you to handle both synchronous and asynchronous errors in the same block of code.
async function secureDataFetch() {
try {
const response = await fetch("https://api.example.com/data");
const data = await response.json();
console.log(data);
} catch (error) {
console.error("Failed to fetch data:", error.message);
} finally {
console.log("Operation attempt complete.");
}
}
Implementation Guidelinesâ
To maintain a professional codebase in 2026, adhere to the following architectural standards:
- Top-Level Await: In modern JavaScript modules (.mjs files or scripts with
type="module"), you can useawaitat the top level of the file without wrapping it in anasyncfunction. - Donât Forget the Try/Catch: An awaited Promise that rejects will throw an exception. If you do not wrap it in a
try/catch, it will result in an "Uncaught (in promise)" error, which can crash your application logic. - Readability over Novelty: Use
async/awaitfor complex logic and multiple steps. For very simple, single-step asynchronous tasks, a traditional.then()may occasionally be more concise. - Refactoring: When moving from Promises to
async/await, ensure you replace.then(val => ...)withconst val = await ...and move the code into the main function body.
By adopting async/await, you transform the "horizontal" growth of callback hell into the "vertical" growth of clean, maintainable, and readable code.
Found this helpful? Share the knowledge...
... or support this project to keep it alive!
Previous
Promises
Next
Fetch API
-
The Async Keyword
-
The Await Keyword
-
Sequential vs. Parallel Execution
- Sequential Execution (Slow)
- Parallel Execution (Fast)
-
Error Handling with Try/Catch
-
Implementation Guidelines
