栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何取消HTTP fetch()请求?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何取消HTTP fetch()请求?

TL / DR:

fetch
现在支持
signal
截至2017年9月20日的参数,但目前 并非所有浏览器似乎都支持此参数

2020更新:
大多数主流浏览器(Edge,Firefox,Chrome,Safari,Opera和其他一些浏览器)都支持该功能,该功能已成为DOM生活标准的一部分。(截至2020年3月5日)

不过,这是我们很快就会看到的更改,因此您应该可以使用

AbortController
s 取消请求
AbortSignal

长版

如何:

它的工作方式是这样的:

第1步
:您创建了一个

AbortController
(现在我只使用了这个)

const controller = new AbortController()

步骤2 :您会收到

AbortController
s信号,如下所示:

const signal = controller.signal

第3步 :您将传递

signal
方式如下:

fetch(urlToFetch, {    method: 'get',    signal: signal, // <------ This is our AbortSignal})

步骤4 :只要需要,就中止:

controller.abort();

这是一个工作原理示例(可在Firefox 57+上运行):

<script>    // Create an instance.    const controller = new AbortController()    const signal = controller.signal        function beginFetching() {        console.log('Now fetching');        var urlToFetch = "https://httpbin.org/delay/3";        fetch(urlToFetch, {     method: 'get',     signal: signal, }) .then(function(response) {     console.log(`Fetch complete. (Not aborted)`); }).catch(function(err) {     console.error(` Err: ${err}`); });    }    function abortFetching() {        console.log('Now aborting');        // Abort.        controller.abort()    }</script><h1>Example of fetch abort</h1><hr><button onclick="beginFetching();">    Begin</button><button onclick="abortFetching();">    Abort</button>


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/442083.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号