简体   繁体   English

如何使用 fetch() api 的响应

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

How to use response from fetch api?如何使用 fetch api 的响应?

i try to return my response, but when i try to print this values in my function, i get undefined , can someone tell me how to use this response in different function?我尝试return我的响应,但是当我尝试在我的 function 中打印此值时,我得到undefined ,有人可以告诉我如何在不同的 function 中使用此响应吗?

my response is an json of nested objects我的回应是嵌套对象的 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;   
  }

thanks for any help谢谢你的帮助

Bottom line, an async function must return a promise to work correctly.底线, async function 必须return promise 才能正常工作。 fetchData has no return value. fetchData没有返回值。 The return response is inside of a .then , and doesn't apply to the fetchData function itself. return response.then内部,不适用于fetchData function 本身。

For the above code, the fewest modifications is simply to return fetch(...) in your fetchData function, like this:对于上面的代码,最少的修改就是在你的fetchData function 中return fetch(...) ,像这样:

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

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

}

Alternatively you could use the async/await syntax for all it's worth, and get rid of your .then s, like this:或者,您可以使用async/await语法,并摆脱您的.then ,如下所示:

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

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

You have to return data in the scope of fetchData function:您必须在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