setTimeout(()=>{
console.log('time out')
},3000)
}
go();
console.log('app')
This is asynchronous code, I want to print app after the delay, but as we know "app" is printed first then "time out".
setTimeout(()=>{
console.log('time out')
},3000)
}
go();
console.log('app')
This is asynchronous code, I want to print app after the delay, but as we know "app" is printed first then "time out".
You can handle the asynchronous task in two ways:-
1st Way:-
function promiseFunction() {
return new Promise((resolve, reject) => {
setTimeout(()=>{
console.log('completed task and resolve');
resolve()
},3000)
})
}
promiseFunction().then(() => {
console.log('all task completed with your message (app)');
})
2nd Way:-
asyncFunction();
function promiseFunction() {
return new Promise((resolve, reject) => {
setTimeout(()=>{
console.log('completed task and resolve');
resolve()
},3000)
})
}
async function asyncFunction() {
await promiseFunction();
console.log('all task completed with your message (app)');
}
P.S please make sure that your await keyword should be in async function.
you can handle async code using promise
function go() {
return new Promise((resolve, reject) => {
setTimeout(()=>{
console.log('time out');
resolve()
},3000)
})
}
go().then(() => {
console.log('app')
})