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
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung InternetNode.js
asyncIteratorChrome Full support 63Edge No support NoFirefox Full support 57IE No support NoOpera Full support 50Safari Full support 11.1WebView Android Full support 63Chrome Android Full support 63Firefox Android No support NoOpera Android Full support 46Safari iOS No support NoSamsung Internet Android Full support 8.0nodejs Full support 10.0.0

Legend

Full support  
Full support
No support  
No support

参见