5

如何在JS中中止fetch请求?

 1 year ago
source link: https://xushanxiang.com/js-abort-fetch.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

如何在JS中中止fetch请求?

作者: xusx 分类: JavaScript 发布时间: 2022-05-19 15:32 浏览:11

Fetch API 现在是在 JavaScript 中发送异步请求的事实上的方式。 这部分是因为 fetch() 方法接受了许多有用的选项。 其中之一是信号选项,可用于中止请求。 要为此选项创建有效值,您可以在创建 AbortController 的新实例后使用 AbortController.signal。 然后,您可以随时使用 AbortController.abort() 取消请求。

// 创建 AbortController
const controller = new AbortController();
const { signal } = controller;

// 执行请求
fetch('https://xushanxiang.com/data', { signal }).then(res => console.log(res));

// 中止请求
controller.abort();
JavaScript

请看 简单的离线视频播放器

如果觉得我的文章对您有用,请随意赞赏。您的支持将鼓励我继续创作!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK