Symbol.asyncIterator

Symbol.asyncIterator 符号指定了一个对象的默认异步迭代器。如果一个对象设置了这个属性,它就是异步可迭代对象,可用于for await...of循环。

描述

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

Symbol.asyncIterator 属性的属性特性:
writable false
enumerable false
configurable false

示例

自定义异步可迭代对象

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

const myAsyncIterable = new Object();
myAsyncIterable[Symbol.asyncIterator] = async function*() {
    yield "hello";
    yield "async";
    yield "iteration!";
};

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

内建异步可迭代对象

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

规范

标准 状态 注释
ECMAScript 2018 (ECMA-262)
Symbol.asyncIterator
Standard

浏览器兼容性

Update compatibility data on GitHub
Desktop Mobile Server
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet Node.js
asyncIterator Chrome Full support 63 Edge No support No Firefox Full support 57 IE No support No Opera Full support 50 Safari Full support 11.1 WebView Android Full support 63 Chrome Android Full support 63 Firefox Android No support No Opera Android Full support 46 Safari iOS No support No Samsung Internet Android Full support 8.0 nodejs Full support 10.0.0

Legend

Full support  
Full support
No support  
No support

参见