-1

I'm trying to check whether my request was sucessecul or not so i had to add an If condition. So, if the condition is true (bad request) i should stop the function and not run the command that come after my condition. My code looks like this:

async function updateUserInfo(userData) {
    const modal = document.querySelector('.userInfos > dialog')
    //modal.close()
    const userToken = getUserToken()

    const nuUserSettings = await fetch(`http://localhost:6278/users`, {
        method: 'PATCH',
        headers: {
            'Content-Type': 'application/json',
            Authorization: `Bearer ${userToken}`,
        },
        body: JSON.stringify(userData)

    })
    
    .then(res => {
        if (res.status === 400) {
            return
        }

    })
    
    console.log('return didnt work function is still running')

    .then(res => res.json()) 
    

}

i tried placing all the leftover code in a 'else' condition but it didn't work out cause .then(res => res.json()) was simply not working

  • 6
    You `return` from `res => { ... }`, not from `updateUserInfo`. – deceze Jan 11 '23 at 15:37
  • handle the status code and json parsing in the same `then`. also you don't need then inside of `async` functions - use `await`. – Daniel A. White Jan 11 '23 at 15:37
  • 2
    Also it's best to get in the habit of *avoiding* `.then()` chaining when you're already using `await`. – Pointy Jan 11 '23 at 15:37
  • There's a `console.log()` between the 2 `.then()`, the second one is not going to work. And why are you using `.then()` in an async function when you could use `await`? – AspectOfTheNoob Jan 11 '23 at 15:44

1 Answers1

-1

It is because you do return inside then block. And then block is not stopping main thread.

What you can do is next

   const response = await fetch(`http://localhost:6278/users`, {
        method: 'PATCH',
        headers: {
            'Content-Type': 'application/json',
            Authorization: `Bearer ${userToken}`,
        },
        body: JSON.stringify(userData)
    });
   if (response.status === 400) return;
   return response.json();

I am not even sure what is this 2nd then -> .then(res => res.json())

Nenad Jovicic
  • 188
  • 1
  • 7