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.

5
  • Personally, I like the way you did it. Commented Sep 26, 2019 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. Commented Sep 26, 2019 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. Commented Sep 26, 2019 at 21:39
  • Why do you want to reject >400 in the first place? Commented Sep 26, 2019 at 21:44
  • I would recommend to avoid mixing await with .then(…) syntax, and to avoid return await. Also consider using response.ok instead of that .status check. Commented Sep 26, 2019 at 21:45

1 Answer 1

-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)} ) 
Sign up to request clarification or add additional context in comments.

3 Comments

aren't you missing a , before err
fetch won't reject on 400
Thanks @AbishekAditya

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.