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 :
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()