AbortController.AbortController()

这篇翻译不完整。请帮忙从英语翻译这篇文章

这是一个实验中的功能
此功能某些浏览器尚在开发中,请参考浏览器兼容性表格以得到在不同浏览器中适合使用的前缀。由于该功能对应的标准文档可能被重新修订,所以在未来版本的浏览器中该功能的语法和行为可能随之改变。

AbortController() 构造函数创建了一个新的AbortController实例

Syntax

var controller = new AbortController();

Parameters

无.

Examples

在下面的这段代码中, 我们将通过Fetch API来下载一段视频.

首先通过AbortController() 构造函数来创建一个controller实例, 然后通过AbortController.signal 属性获取到它的关联对象AbortSignal 的引用.

当 fetch request 初始化后, 将 AbortSignal 作为一个选项传入请求的选项参数中 (如下 {signal}). 这将signal,controller与fetch请求关联起来, 允许我们通过调用AbortController.abort()来取消fetch请求, 正如下第二个事件监听器所示.

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

var downloadBtn = document.querySelector('.download');
var abortBtn = document.querySelector('.abort');

downloadBtn.addEventListener('click', fetchVideo);

abortBtn.addEventListener('click', function() {
  controller.abort();
  console.log('Download aborted');
});

function fetchVideo() {
  ...
  fetch(url, {signal}).then(function(response) {
    ...
  }).catch(function(e) {
    reports.textContent = 'Download error: ' + e.message;
  })
}

提示: 当abort() 被调用,  fetch() promise 将会抛出一个AbortError对象.

你可以在GitHub上找到一个完整的使用示例 — see abort-api (see it running live also).

Specifications

Specification Status Comment
DOM
AbortController()
Living Standard Initial definition

Browser compatibility

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidEdge MobileFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
Basic support
Experimental
Chrome Full support 66Edge Full support 16Firefox Full support 57IE No support NoOpera Full support 53Safari Full support 11.1WebView Android Full support 66Chrome Android Full support 66Edge Mobile Full support 16Firefox Android Full support 57Opera Android Full support 53Safari iOS Full support 11.1Samsung Internet Android No support No

Legend

Full support  
Full support
No support  
No support
Experimental. Expect behavior to change in the future.
Experimental. Expect behavior to change in the future.

See also

文档标签和贡献者

此页面的贡献者: xiiiAtCn
最后编辑者: xiiiAtCn,