aboutsummaryrefslogtreecommitdiff
path: root/files/zh-cn/web/javascript/reference/global_objects/symbol/asynciterator/index.html
blob: f0c05da9ab84430e29ccb00f170225d80e6b92e4 (plain)
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
---
title: Symbol.asyncIterator
slug: Web/JavaScript/Reference/Global_Objects/Symbol/asyncIterator
translation_of: Web/JavaScript/Reference/Global_Objects/Symbol/asyncIterator
---
<div>{{JSRef}}</div>

<p><code><strong>Symbol.asyncIterator</strong></code> 符号指定了一个对象的默认异步迭代器。如果一个对象设置了这个属性,它就是异步可迭代对象,可用于<code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of">for await...of</a></code>循环。</p>



<h2 id="描述">描述</h2>

<p><code>Symbol.asyncIterator</code> 是一个用于访问对象的<code>@@asyncIterator</code>方法的内建符号。一个异步可迭代对象必须要有<code>Symbol.asyncIterator</code>属性。</p>

<p>{{js_property_attributes(0,0,0)}}</p>

<h2 id="示例">示例</h2>

<h3 id="自定义异步可迭代对象">自定义异步可迭代对象</h3>

<p>你可以通过设置<code>[Symbol.asyncIterator]</code>属性来自定义异步可迭代对象。</p>

<pre class="brush: js">const myAsyncIterable = new Object();
myAsyncIterable[Symbol.asyncIterator] = async function*() {
    yield "hello";
    yield "async";
    yield "iteration!";
};

(async () =&gt; {
    for await (const x of myAsyncIterable) {
        console.log(x);
        // expected output:
        //    "hello"
        //    "async"
        //    "iteration!"
    }
})();
</pre>

<h3 id="内建异步可迭代对象">内建异步可迭代对象</h3>

<p>目前没有默认设定了<code>[Symbol.asyncIterator]</code>属性的JavaScript内建的对象。不过,WHATWG(网页超文本应用技术工作小组)Streams会被设定为第一批异步可迭代对象,<code>[Symbol.asyncIterator]</code> 最近已在设计规范中落地。</p>

<h2 id="规范">规范</h2>

<table class="standard-table">
 <thead>
  <tr>
   <th scope="col">标准</th>
   <th scope="col">状态</th>
   <th scope="col">注释</th>
  </tr>
 </thead>
 <tbody>
  <tr>
   <td>{{SpecName('ES2018', '#sec-symbol.asynciterator', 'Symbol.asyncIterator')}}</td>
   <td>{{Spec2('ES2018')}}</td>
   <td></td>
  </tr>
 </tbody>
</table>

<h2 id="浏览器兼容性">浏览器兼容性</h2>



<p>{{compat("javascript.builtins.Symbol.asyncIterator")}}</p>

<h2 id="参见">参见</h2>

<ul>
 <li><a href="/en-US/docs/Web/JavaScript/Reference/Iteration_protocols">Iteration protocols</a></li>
 <li><a href="/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of">for await... of</a></li>
</ul>