使用 fetch JS 进行异步/等待

13 javascript fetch async-await

我在创建一个函数时遇到问题,该函数将停止所有代码直到完成。我想制作异步/等待。在该函数中,我应该进行 fetch,但当我返回结果代码时,它会显示 Promise {}:

const request = async (url) => {
    const response = await fetch(url);
    const json = await JSON.stringify(response.json());
    return json;
}
let tree = request('humans.json');

console.log(tree);
Run Code Online (Sandbox Code Playgroud)

Ami*_*han 7

async 函数可以通过两种方式调用。

  1. 使用 then 方法
request.then(resp => console.log(resp)).catch(e => console.log(e));
Run Code Online (Sandbox Code Playgroud)
  1. 使用await - 要使用await,您需要一个异步函数,否则await 关键字将给出错误并且只能在异步函数内调用。
async function exe() {
 try {
  const result = await request(); // Now this will wait till it finished
  console.log(result);
 } catch(e) {
  console.log(e);
 }
}
Run Code Online (Sandbox Code Playgroud)


Uza*_*yed 6

当您在函数之前添加 async 时,这意味着该函数将返回一个承诺作为响应,并且为了使用该结果您需要执行类似的操作

tree.then(()=>{
//Promise Successful, Do something
}).catch(()=>{
//Promise Failed, Do something
})
Run Code Online (Sandbox Code Playgroud)

如果你想使用 fetch,你可以这样做

fetch('humans.json')
  .then(response => response.json())
  .then(data => console.log(data)).catch(()=>{
   ///Exception occured do something
})
Run Code Online (Sandbox Code Playgroud)

上面的 fetch 语句将log the json data into console提供humans.json 有关 fetch api 工作原理的更多信息,您可以参考 MDN 这里