DEV Community

Nanthini Ammu
Nanthini Ammu

Posted on

JS async and await

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();
Enter fullscreen mode Exit fullscreen mode

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))
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

Syntax Rules async:

  • The async keyword placed before a function declaration or expression.
  • Makes the function always return a Promise, even if a plain value is returned.

await keyword :

  • Pauses execution of the async function until the Promise resolves.
  • Returns the resolved value of the Promise.
  • 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
Enter fullscreen mode Exit fullscreen mode
function greet(){
        return Promise.resolve("Hello")
}

async function asyncfun(){
        const gret = await greet();
        console.log(gret);
}

asyncfun();
Enter fullscreen mode Exit fullscreen mode
async function fetchUser(){
        const response = await fetch("https://jsonplaceholder.typicode.com/posts");
         const data = await response.json();
        console.log(data);
}

fetchUser();
Enter fullscreen mode Exit fullscreen mode
function wait(ms){

        return new Promise((resolve,reject) => setTimeout(()=>resolve() ,ms));
}

async function makeOrder(){
        console.log("Order Placed");
        await wait(1000);
        console.log("Food is being prepared");
        await wait(3000);
        console.log("Order Ready");
}

makeOrder();
Enter fullscreen mode Exit fullscreen mode

Error handling with try/catch :

async function fetchUser(){
        try{
         const response = await fetch("https://jsonplaceholder.typicode.com/post/1");
         if(!response.ok)
         {
                throw new Error()
         }
         const data = await response.json();
         console.log(data);
        }
        catch(err){
        console.log(err);
        }
        finally {
        console.log("Runs always!");
         }

}

fetchUser();

Enter fullscreen mode Exit fullscreen mode

Top comments (0)