javascript 如何取消中止已中止的获取

pes8fvy9  于 2023-06-28  发布在  Java
关注(0)|答案(1)|浏览(128)

我放弃了,获取但我不能再次调用获取

const startFetch = document.querySelector(" #startFetch");
const stopFetch = document.querySelector("#stopFetch");

const controller = new AbortController();
const todos = async() => {
  fetch("https://jsonplaceholder.typicode.com/todos", {
      signal: controller.signal,
    })
    .then((data) => data.json())
    .then((todos) => {
      console.log(todos);
    })
    .catch((err) => {
      console.log(err.message);
    });
};
startFetch.addEventListener("click", todos);
stopFetch.addEventListener("click", () => {
  controller.abort();
});
<button id="startFetch">startFetch</button>
<button id="stopFetch">stopFetch</button>

我需要取消中止一个已中止的获取

vuktfyat

vuktfyat1#

你不能。一个被中止的获取关闭了连接,你需要发出一个单独的新请求。中止的信号保持该状态,您需要创建一个新的信号(和一个新的AbortController)。

const stopFetch = document.querySelector("#stopFetch");

let controller;
const todos = async() => {
  controller = new AbortController();
  fetch("https://jsonplaceholder.typicode.com/todos", {
      signal: controller.signal,
    })
    .then(data => data.json())
    .then(todos => {
      console.log(todos);
    }, err => {
      console.log(err.message);
    }).finally(() => {
      controller = null;
    });
};
startFetch.addEventListener("click", todos);
stopFetch.addEventListener("click", () => {
  if (controller) {
    controller.abort();
  } else {
    console.log("no active request");
  }
});
<button id="startFetch">startFetch</button>
<button id="stopFetch">stopFetch</button>

相关问题