Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

取消请求的几种方式 #43

Open
imfenghuang opened this issue Jun 19, 2024 · 0 comments
Open

取消请求的几种方式 #43

imfenghuang opened this issue Jun 19, 2024 · 0 comments

Comments

@imfenghuang
Copy link
Owner

imfenghuang commented Jun 19, 2024

取消请求的几种方式

1. Ajax

https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest/abort

如果该请求已被发出,XMLHttpRequest.abort()  方法将终止该请求。当一个请求被终止,它的  readyState  将被置为  XMLHttpRequest.UNSENT (0),并且请求的  status  置为 0。

var xhr = new XMLHttpRequest(),
  method = "GET",
  url = "https://developer.mozilla.org/";

xhr.open(method, url, true);

xhr.send();

if (condition) {
  xhr.abort();
  console.log(xhr.status, xhr.readyState);
}

2. Fetch

https://developer.mozilla.org/zh-CN/docs/Web/API/AbortController

使用 AbortController

const controller = new AbortController();
const signal = controller.signal;

fetch(url, { signal })
  .then((res) => {
    console.log(res);
  })
  .catch((err) => {
    console.log(err);
  });

// 取消请求
if (condition) {
  controller.abort();
}
// 当 abort() 被调用时,这个 fetch() promise 将 reject 一个名为 AbortError 的 DOMException

3. Axios

https://axios-http.com/zh/docs/cancellation

3.1. AbortController

  • v0.22.0 启用
import axios from "axios";

const controller = new AbortController();
const signal = controller.signal;

axios
  .get("https://your-server.com/api", {
    signal,
  })
  .catch(function (e) {
    if (axios.isCancel(e)) {
      console.error("Operation canceled");
    } else {
      // todo
    }
  });
  
controller.abort();

3.2. CancelToken

  • v0.22.0 弃用
import axios from "axios";

const CancelToken = axios.CancelToken;
const cancelTokenSource = CancelToken.source();

axios
  .get("https://your-server.com/api", {
    cancelToken: cancelTokenSource.token,
  })
  .catch(function (e) {
    if (axios.isCancel(e)) {
      console.error(e.message);
    } else {
      // todo
    }
  });

cancelTokenSource.cancel("Operation canceled");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant