Search code examples
javascriptfetch-api

how to know the state of a response with fetch Api javascript?


function boleta(){
    var check = false;
    var formboleta = new FormData();
    formboleta.append("num_boleta", data2.boletas[id].num_boleta);
    formboleta.append("created_at", data2.boletas[id].created_at);
    formboleta.append("total", data2.boletas[id].total);
    //arreglo id productos
    for(let k = 0; k < arr.length; k++){
        formboleta.append("productos", data2.boletas[id].productos[k].id);
    }
    var requestOptions = {
      method: 'POST',
      body: formboleta,
      redirect: 'follow'
    };
    let status;
    fetch("url_goes_here", requestOptions)
    .then((response) => {
      status = response.status;
      return response.json();
    })
    .catch(error => console.log('error', error));
    //---------------------------------------------
}

Hi guys, i want to know how to get the state of a response, to make an if and execute another function if the state is 200 or success.

in the first response i want to make if status is ok, call another function which in this case it will be function cliente();.

The function cliente(); will do another post and create a customer for this ticket, but i can't call it when the ticket( by ticket i mean the function boleta, which inside creates a boleta(ticket)) isn't done already.


Solution

  • You can get the status of an HTTP request as

    .then((response) => {
        status = response.status;
        return response.json();
      })
    

    If you somehow want status in second then, then create a variable and store the status after getting the response like

    let status;
    fetch("https://jsonplaceholder.typicode.com/todos/1")
      .then((response) => {
        // Get status using response.status
        status = response.status;
        console.log(`status in first then ${status}`);
        return response.json();
      })
      .then((json) => {
        // Get status in after the first .then
        console.log(`status in second then 4 ${status}`);
        console.log(console.log(json));
      });