react-native fetch return status code + json

前端 未结 2 750
你的背包
你的背包 2021-02-14 21:32

I use fetch in react-native to make API calls.

I need to get status code (200 , 401, 404 ) and the response data.

This work to get the response data :



        
2条回答
  •  别跟我提以往
    2021-02-14 22:23

    response.json() returns a promise, you should wait until it will be fulfilled. To do that you can use Promise.all with array of two elements: statusCode and response.json() call:

    return fetch(url)
      .then(response => {
        const statusCode = response.status;
        const data = response.json();
        return Promise.all([statusCode, data]);
      })
      .then([res, data] => {
        console.log(res, data);
      })
      .catch(error => {
        console.error(error);
        return { name: "network error", description: "" };
      });
    

    //EDIT you can create a function who process the response

    function processResponse(response) {
      const statusCode = response.status;
      const data = response.json();
      return Promise.all([statusCode, data]).then(res => ({
        statusCode: res[0],
        data: res[1]
      }));
    }
    

    and use it the then()

     return fetch(url)
        .then(processResponse)
        .then(res => {
            const { statusCode, data } = res;
            console.log("statusCode",statusCode);
            console.log("data",data);
        }) .catch(error => {
        console.error(error);
        return { name: "network error", description: "" };
      });
    

提交回复
热议问题