0
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".

Amaan Imtiyaz
  • 254
  • 6
  • 16

2 Answers2

5

You can handle the asynchronous task in two ways:-

  1. With Promise and then method
  2. With async/await method

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.

JAY PATEL
  • 559
  • 4
  • 17
1

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')
})
Ankur Patel
  • 478
  • 3
  • 6