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

1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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')
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.