What is async and await?
- async and await are 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. But 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.
- 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(Moderna 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 async keyword placed before a function declaration or expression.
- Makes the function always return a Promise, even if a plain value is returned.
- Only inside an async function await can be used.
async function greet(){
return "Hello";
}
console.log(greet()); //Promise {<fulfilled>: 'Hello'}
greet().then((response)=> console.log(response)); //Hello
Top comments (0)