1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
|
---
title: AbortController.AbortController()
slug: Web/API/FetchController/AbortController
tags:
- AbortController
- Constructor
- Fetch
translation_of: Web/API/AbortController/AbortController
---
<div>{{APIRef("DOM")}}{{SeeCompatTable}}</div>
<p><strong><code>AbortController()</code></strong> 构造函数创建了一个新的<code>AbortController实例</code></p>
<h2 id="Syntax">Syntax</h2>
<pre class="brush: js">var controller = new AbortController();</pre>
<h3 id="Parameters">Parameters</h3>
<p>无.</p>
<h2 id="Examples">Examples</h2>
<p>在下面的这段代码中, 我们将通过<a href="/en-US/docs/Web/API/Fetch_API">Fetch API</a>来下载一段视频.</p>
<p>首先通过{{domxref("AbortController.AbortController","AbortController()")}} 构造函数来创建一个controller实例, 然后通过{{domxref("AbortController.signal")}} 属性获取到它的关联对象{{domxref("AbortSignal")}} 的引用.</p>
<p>当 <a href="/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch">fetch request</a> 初始化后, 将 <code>AbortSignal</code> 作为一个选项传入请求的选项参数中 (如下 <code>{signal}</code>). 这将signal,controller与fetch请求关联起来, 允许我们通过调用{{domxref("AbortController.abort()")}}来取消fetch请求, 正如下第二个事件监听器所示.</p>
<pre class="brush: js">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;
})
}</pre>
<div class="note">
<p><strong>提示</strong>: 当<code>abort()</code> 被调用, <code>fetch()</code> promise 将会抛出一个<code>AbortError对象</code>.</p>
</div>
<p>你可以在GitHub上找到一个完整的使用示例 — see <a href="https://github.com/mdn/dom-examples/tree/master/abort-api">abort-api</a> (<a href="https://mdn.github.io/dom-examples/abort-api/">see it running live also</a>).</p>
<h2 id="Specifications">Specifications</h2>
<table class="standard-table">
<tbody>
<tr>
<th scope="col">Specification</th>
<th scope="col">Status</th>
<th scope="col">Comment</th>
</tr>
<tr>
<td>{{SpecName('DOM WHATWG', '#dom-abortcontroller-abortcontroller', 'AbortController()')}}</td>
<td>{{Spec2('DOM WHATWG')}}</td>
<td>Initial definition</td>
</tr>
</tbody>
</table>
<h2 id="Browser_compatibility">Browser compatibility</h2>
<p>{{Compat("api.AbortController.AbortController")}}</p>
<h2 id="See_also">See also</h2>
<ul>
<li><a href="/en-US/docs/Web/API/Fetch_API">Fetch API</a></li>
</ul>
|