繁体   English   中英

如何使用 fetch() api 的响应

[英]How to use response from fetch() api

如何使用 fetch api 的响应?

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

我的回应是嵌套对象的 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;   
  }

谢谢你的帮助

底线, async function 必须return promise 才能正常工作。 fetchData没有返回值。 return response.then内部,不适用于fetchData function 本身。

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

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

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

}

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

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

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

您必须在fetchData function的fetchData中返回数据:

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

    const response = await fetch(url, {
        method: 'post',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ 
            //...
        })
    });

    return response;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM