【问题标题】:converting promise chain to async/await将 Promise 链转换为 async/await
【发布时间】:2022-01-27 13:55:37
【问题描述】:
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 !!!!")

上面的代码记录 Calling testFunc !!!! 然后 Done !!!! 然后 Hello there Sam!
在这种情况下如何使用 async/await 来记录 Calling testFunc !!!! 然后 Hello there Sam! 然后 Done !!!!
提前致谢

【问题讨论】:

    标签: asynchronous async-await


    【解决方案1】:

    因为 '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()
    

    【讨论】:

    • 哇,太棒了。解决了我的问题!谢谢!
    猜你喜欢
    • 2019-08-11
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 2019-12-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多