2

I have a 400 returning a body with errors I need to get at. However, since fetch doesn't actually fail that status code, I handle it in the then and return a rejected Promise. But, because then generally returns a Promise, I can't issue a reject without awaiting the response from json().

dispatch({
  type: 'LOGIN',
  payload: fetch(`${host}/api/signin/`, {
    method: 'POST',
    body: data
  }).then(async res => {
    if (res.status >= 400) {
      return Promise.reject(await res.json());
    }

    return await res.json();
  })
});

Is there a better way to handle this? It's technically working, but I feel like I'm probably handling it wrong by making then synchronous.

Mike Perrenoud
  • 66,820
  • 29
  • 157
  • 232
  • Personally, I like the way you did it. – Lonnie Best Sep 26 '19 at 21:34
  • 1
    The normal process is to use two .then's, but i see no real problem with combining them using async/await. – Kevin B Sep 26 '19 at 21:36
  • I've created a function in my library that wraps fetch with an async function of my own and I await fetch itself within that function to avoid `then` completely. – Lonnie Best Sep 26 '19 at 21:39
  • Why do you want to reject >400 in the first place? – TheMaster Sep 26 '19 at 21:44
  • I would recommend to [avoid mixing `await` with `.then(…)` syntax](https://stackoverflow.com/a/54387912/1048572), and to [avoid `return await`](https://stackoverflow.com/a/43985067/1048572). Also consider using [`response.ok`](https://developer.mozilla.org/en-US/docs/Web/API/Response/ok) instead of that `.status` check. – Bergi Sep 26 '19 at 21:45

1 Answers1

-1

I feel like I am missing something here, but couldn't you just console log the rejection?

somepromise.then(
  res => { ... },
  err => { console.log(err)}
)
alex067
  • 3,159
  • 1
  • 11
  • 17