0

I'm trying to fetch data with this method and its working fine. But Now I want to send the status code to the next then block but when I send it as below the promise fails and responseJson fails some garbage value in console. How to attempt to send two parameters to next then block

         fetch(NEW_URL, options)
          
          .then((response) => {
            //console.log(response.status); // Will show you the status
           

            if(response.status === 400) {
              
              reject('A unknown error has occurred. Please try again later.');
            }
            if (!response.ok) {
                
                reject("server error.");
            }
            return [response, response.status];
        })
          .then(([response, status])=>{
            return [response.json(), status]
          })
          .then(([responseJson, status]) => {
           //status received here but responseJson is a failed promise
            console.log("RESPONSE ", JSON.stringify(responseJson) +" "+NEW_URL);
            resolve(responseJson);
          }).catch((message)=> {
            reject(message)
          });

I get something like RESPONSE {"_40":0,"_65":0,"_55":null,"_72":null} https://ap.... printed in console.

Can someone help me out. Thanks in advance

1 Answers1

3

Try this solution

fetch(NEW_URL, options)
  .then((response) => {
    //console.log(response.status); // Will show you the status

    if (response.status === 400) {
      reject("A unknown error has occurred. Please try again later.");
    }
    if (!response.ok) {
      reject("server error.");
    }
    return [response, response.status];
  })
  .then(([response, status]) => {
    //Try this solution
    //You need to convert response to JSON format otherwise you get dumb values
    response.json().then((responseData) => {
      console.log("RESPONSE ", responseData + " " + NEW_URL);
    });
  })
  .then(([responseJson, status]) => {
    //status received here but responseJson is a failed promise
    // console.log("RESPONSE ", JSON.stringify(responseJson) + " " + NEW_URL);
    // resolve(responseJson);
  })
  .catch((message) => {
    reject(message);
  });
Akila Devinda
  • 5,054
  • 3
  • 19
  • 35