如何使用 fetch Api javascript 了解响应的状态?

问题描述 投票:0回答:1
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));
    //---------------------------------------------
}

大家好,我想知道如何获取响应的状态,如果状态为 200 或成功,则创建一个 if 并执行另一个函数。

在我想要做出的第一个响应中,如果状态正常,请调用另一个函数 在本例中它将是 function cliente();.

函数 cliente();将做另一篇文章并为这张票创建一个客户,但是当票(票我的意思是函数 boleta,里面创建了一个 boleta(票))尚未完成时我无法调用它。

javascript fetch-api
1个回答
0
投票

您可以通过以下方式获取 HTTP 请求的状态

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

如果你想在第二秒获得状态

then
,那么创建一个变量并在得到响应后存储状态

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

© www.soinside.com 2019 - 2024. All rights reserved.