我应该将 fetch() 与 .then 一起使用还是 async/await

Lea*_*dro 7 javascript fetch promise async-await

以下代码片段给了我相同的结果。使用.thenasync/await来获取数据有什么区别?

// Code 1

function fetchData() {
  fetch(url)
      .then(response => response.json())
      .then(json => console.log(json))
}



// Code 2

async function fetchData() {
  const response = await fetch(url);
  const json = await response.json();
  console.log(json);
}
Run Code Online (Sandbox Code Playgroud)

Vla*_*d L 6

async 和await 只是语法糖。它们与 \xe2\x80\x9cthen\xe2\x80\x9d 执行相同的操作,但通常认为 wait 语法更可取,因为它允许避免嵌套 then 语句,并且可以说更容易阅读。

\n