将承诺链转换为 async/await

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 !!!!")

上面的代码记录 调用 testFunc !!!! 然后 完成 !!!! 然后 你好 Sam !
在这种情况下我如何使用 async/await 来记录 调用 testFunc !!!! 然后 你好山姆! 然后 完成!!!!
提前致谢

因为 'textFunc' 是异步的,这意味着它需要几秒钟才能完成,console.log('done') 将在 .then(...) 之前执行。所以你可以只添加 console.log('done').then(...) 部分,或者使用类似下面的代码。

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

您可能还必须将所有内容包装在异步函数中

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

someFunction()