跳至主要內容
取消 Promise

取消 Promise

fetch 和 axios 都支持使用AbortController的方式来取消请求。以 fetch 为例,想要取消请求,分为三步:

const url = "https://blog.yuchen.tech/";

// 1. 创建AbortController
const controller = new AbortController();
const signal = controller.signal;

// 2. 发送请求时传入AbortController的signal
fetch(url, { signal })
  .then((response) => {
    console.log(response);
  })
  .catch((error) => {
    console.log(error);
  });

// 3. 使用AbortController的abort方法来取消请求
controller.abort();
// Node 下输出
// DOMException [AbortError]: This operation was aborted
// 浏览器下输出
// DOMException: The user aborted a request.

Yuchen大约 2 分钟JSJSTSSnippets