等待异步函数

时间:2021-05-30 08:19:40

标签: javascript asynchronous async-await

我真的不知道何时/如何使用异步和等待。例如,我有这个返回承诺的函数:

async function fn1(){
  return await fetch('localhost:3000')
} 

现在我有两个选择:

  1. 使用.then

    fn1.then((result) => {
      console.log(result)
    })
    
  2. 使用await

    const data = await fn1()
    console.log(data)
    

我更喜欢第二种方法,但这会让我将它包装在一个 async 函数中,我必须await 或使用 .then 来使用它。

我看过一些同时使用 async/await.then 的教程,但据我所知,这不是很好的做法。

0 个答案:

没有答案