首页 > 解决方案 > 如何使用 fetch() api 的响应

问题描述

如何使用来自 fetch api 的响应?

我尝试return我的回应,但是当我尝试在我的函数中打印这个值时,我得到undefined,有人可以告诉我如何在不同的函数中使用这个响应吗?

我的响应是嵌套对象的 json

  async fetchData() {
    const url = `...`;

    fetch(url, {
        method: 'post',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ 
            //
        })
    }).then((response) => response.json())
      .then(response => {;
        console.log(response) //correct response
        return response;
      })

  }

  async getDataFromFetchApi() {
      const data= await this.fetchData();
      console.log(data); // undefined

      if(data != undefined){
        throw new BadRequestException();
     }

      return data;   
  }

谢谢你的帮助

标签: javascripttypescriptfetch

解决方案


归根结底,async函数必须return保证能够正常工作。fetchData没有返回值。位于return responsea 内部,.then不适用于fetchData函数本身。

对于上面的代码,最少的修改就是return fetch(...)在你的fetchData函数中,像这样:

async fetchData() {
  const url = `...`;

  return fetch(/* ... */)
    .then((response) => response.json())
    .then(response => {
      console.log(response) //correct response
      return response;
    })

}

或者,您可以尽其所能使用async/await语法,并摆脱您.then的 s,如下所示:

async fetchData() {
  const url = `...`;

  const resp = await fetch(/* ... */);
  const json = await resp.json();
  console.log(json);
  return json;
}

推荐阅读