<< November 2017 | Home

Note to self - use Promise.all instead of simply resp.text()

Was frustrated that when using fetch and the promise chain that once you returned a promise to get the response text (or JSON) you no longer had access to the response object in the next promise without having a state variable. I often return an error message in the response to inform the user what went wrong but I cannot see what happened based on status code without the response object. Well at least as far as I can read the API on MDN. My solution is to resolve using Promise.all instead of simply resp.text() or resp.json() as below. That's all...

fetch('/foo').then(resp => {
   return Promise.all([Promise.resolve(resp), resp.text()])
}).then(values => {
   const resp = values[0]
   const txt = values[1]
   if (resp.status !== 200) {
      // duh!!!
   } else {
      // oh the joy
   }
})