2

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); }) } })

1
  • change .then(resp => { return [resp.json(), resp.status] to .then(resp => { return resp.json() and then in next .then your data will have entire resp object. Extract what you need from data Commented Jun 9, 2021 at 1:55

2 Answers 2

2
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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.