Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

converting promise chain to async/await

function testFunc(name) {
    return new Promise(resolve => {
        setTimeout(() => resolve('Hello there ' + name + '!'), 3000)
      })
}

console.log("Calling testFunc !!!!")
testFunc('Sam').then(data => console.log(data))
console.log("Done !!!!")

The code above logs Calling testFunc !!!! then Done !!!! then Hello there Sam!

How can I use async/await in this situation to log Calling testFunc !!!! then Hello there Sam! then Done !!!!

Thanks in advance

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Because ‘textFunc’ is asynchronous, meaning it takes a couple seconds to complete, console.log('done') will get executed before .then(...). So you can just add console.log('done') into the .then(...) part, or use something like the code below.

console.log("Calling testFunc !!!!")
let data = await testFunc('Sam')
console.log(data)
console.log("Done !!!!")

you might also have to wrap everything in an async function

async someFunction() {
    console.log("Calling testFunc !!!!")
    let data = await testFunc('Sam')
    console.log(data)
    console.log("Done !!!!")
}

someFunction()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading