JS async and await
Published: (May 6, 2026 at 07:47 AM EDT)
2 min read
Source: Dev.to
Source: Dev.to
What is async and await?
asyncandawaitare used to handle asynchronous operations in a cleaner way.
Why Do We Need Asynchronous Code?
- JavaScript is single‑threaded — it can only do one thing at a time. Many real‑world tasks (fetching data from a server, reading a file, waiting for a timer) take time. If JS waited for each of these to finish before moving on, the browser would freeze and become unresponsive.
- Asynchronous programming allows JS to start a slow task, continue running other code, and then come back to handle the result when it’s ready — without blocking the main thread.
Typical use cases
- Fetching data from an API (network request)
- Reading/writing files (Node.js)
setTimeout/setInterval(timers)- Database queries
Evolution: Callbacks → Promises → Async/Await
Callbacks (Old way)
setTimeout(() => {
console.log("Prepping");
setTimeout(() => {
console.log("Cooking");
setTimeout(() => {
console.log("Eating");
}, 3000);
}, 5000);
}, 1000);
prepping();
Promises (Better)
function prepping() {
return new Promise((resolve, reject) =>
setTimeout(() => resolve("Prepping"), 1000)
);
}
function cooking() {
return new Promise((resolve, reject) =>
setTimeout(() => resolve("Cooking"), 5000)
);
}
function eating() {
return new Promise((resolve, reject) =>
setTimeout(() => resolve("Eating"), 3000)
);
}
prepping()
.then(response => {
console.log(response);
return cooking();
})
.then(response => {
console.log(response);
return eating();
})
.then(response => console.log(response));
async/await (Modern and Cleanest)
function prepping() {
return new Promise((resolve, reject) =>
setTimeout(() => resolve("Prepping"), 1000)
);
}
function cooking() {
return new Promise((resolve, reject) =>
setTimeout(() => resolve("Cooking"), 5000)
);
}
function eating() {
return new Promise((resolve, reject) =>
setTimeout(() => resolve("Eating"), 3000)
);
}
async function asynfunction() {
const prep = await prepping();
console.log(prep);
const cook = await cooking();
console.log(cook);
const eat = await eating();
console.log(eat);
}
asynfunction();
Syntax Rules
- The
asynckeyword is placed before a function declaration or expression. - It makes the function always return a
Promise, even if a plain value is returned. awaitcan be used only inside anasyncfunction.
async function greet() {
return "Hello";
}
console.log(greet()); // Promise { : 'Hello' }
greet().then(response => console.log(response)); // Hello