简体   繁体   中英

How to use response from fetch() api

How to use response from 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?

my response is an json of nested objects

  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. fetchData has no return value. The return response is inside of a .then , and doesn't apply to the fetchData function itself.

For the above code, the fewest modifications is simply to return fetch(...) in your fetchData function, like this:

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 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:

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

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

    return response;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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