Richardson
Richardson

Reputation: 2285

cannot resolve promise using fetch

I cannot resolve this promise using fetch I want 2 values to go the .then(data) I want to use the status as wall as the JSON that I got form the back-end, then inherit the incoming status but the resp.json is always showing a and I cannot access its value any idea ?

fetch('/signup', {
      credentials: "same-origin",
      mode: "same-origin",
      method: 'POST',
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(inputJSON)
    })

      .then(resp => {
        return [resp.json(), resp.status]
    })
      .then(function (data) {
      
        console.log(data);
        let Status = data[1]
        
        let jsonData = data[0]
        let p = jsonData.then(e => { return e })
        console.log(p);

      })
  }
})

Upvotes: 2

Views: 273

Answers (2)

Gyanendro Kh
Gyanendro Kh

Reputation: 405

fetch('/signup', {
  credentials: 'same-origin',
  mode: 'same-origin',
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify(inputJSON),
})
  .then((resp) => {
    return Promise.all([resp.json(), Promise.resolve(resp.status)]);
  })
  .then(function (data) {
    const [json, status] = data;

    console.log(json);
    console.log(status);
  });

resp.json() returns a Promise, resp.status returns a Number and .then if returns a Promise will resolve it for you but if any other datatype is returned it will not do anything.

So, resp.status is converted to Promise.resolve(resp.status) to turn it into a Promise and returns Promise.all([resp.json(), Promise.resolve(resp.status)]) from .then.

Promise.all will turn multiple Promises into one.

Upvotes: 2

CertainPerformance
CertainPerformance

Reputation: 370729

Return a Promise.all to pass both values down the chain:

fetch('/signup', {
    credentials: "same-origin",
    mode: "same-origin",
    method: 'POST',
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(inputJSON)
})

    .then(resp => {
        return Promise.all([resp.json(), resp.status]);
    })

Or, even better, use async/await, the control flow will be clearer:

const resp = await fetch('/signup', {
    credentials: "same-origin",
    mode: "same-origin",
    method: 'POST',
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(inputJSON)
});
const result = await resp.json();
// do stuff with result and with resp.status

Make sure to catch possible errors in both cases.

Upvotes: 2

Related Questions