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

Published by

lekkim

Positive, competent, out-spoken, frank and customer focused architect and developer with a strong foundation in web, cloud and product development. I'm a strong advocate for API first and cloud based solutions and development. I have a knack for being able to communicate and present technically complicated matters in conference, customer and training settings. I've previously acted as team member and leader in a product organisation.