DEV Community

kheersagar parja
kheersagar parja

Posted on

Asynchronous to Synchronous JavaScript

Popular JavaScript Interview Question

How to Convert Asynchronous code to Synchronous code ?
Promises can be used to convert Asynchronous code to Synchronous code.

Example
Asynchronous setTimeout Function

console.log("Before setTimeout")

setTimeout(()=>{
    console.log("Inside setTimeout")
},1000)

console.log("After setTimeout")

Enter fullscreen mode Exit fullscreen mode

Output

Before setTimeout
After setTimeout
Inside setTimeout
Enter fullscreen mode Exit fullscreen mode

Convert Asynchronous setTimeout Function to Synchronous

console.log("Before setTimeout")

//await will wait for JS to resolve the promise
await new Promise((resolve,reject)=>{
   setTimeout(()=>{
   //after 1000ms promise will be resolved
    resolve(console.log("Inside setTimeout")) 
   },1000) 
})

console.log("After setTimeout")
Enter fullscreen mode Exit fullscreen mode

Output

Before setTimeout
Inside setTimeout
After setTimeout
Enter fullscreen mode Exit fullscreen mode

Top comments (0)