Skip to content

Async / Await

Before ES2017, we primarily used Promises with .then() and .catch().
But once calls were chained, the code became hard to read.

async and await allow you to write asynchronous code like synchronous code, making it clearer and more readable.


An async function always returns a Promise.

async function greet() {
return "Hello";
}
greet().then(msg => console.log(msg)); // Hello

The await keyword pauses execution of the async function until the Promise resolves.
This avoids chaining multiple .then() calls.

function wait(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function start() {
console.log("Waiting...");
await wait(2000);
console.log("Finished after 2 seconds");
}
start();

fetch("https://jsonplaceholder.typicode.com/posts/1")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error("Error:", error));
async function getPost() {
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);
}
}
getPost();

Same result, but much more readable.


async function test() {
try {
let response = await fetch("https://jsonplaceholder.typicode.com/posts/1");
let data = await response.json();
console.log(data);
} catch (e) {
console.error("Error:", e);
}
}

  • Use async/await to improve code readability.
  • Always handle errors with try/catch.
  • ⚠️ await can only be used inside an async function.
  • To run multiple Promises in parallel, prefer Promise.all rather than sequential await calls.

Example: running multiple Promises in parallel

Section titled “Example: running multiple Promises in parallel”
async function loadData() {
let [posts, users] = await Promise.all([
fetch("/posts").then(r => r.json()),
fetch("/users").then(r => r.json())
]);
console.log(posts, users);
}