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")
Output
Before setTimeout
After setTimeout
Inside setTimeout
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")
Output
Before setTimeout
Inside setTimeout
After setTimeout
Top comments (0)