Symbol.asyncIterator well-known symbol specifies the default AsyncIterator for an object. If this property is set on an object, it is an async iterable and can be used in a for await...of loop.

描述

Symbol.asyncIterator symbol is a builtin symbol that is used to access an object's @@asyncIterator method. In order for an object to be async iterable, it must have a Symbol.asyncIterator key.

特性属性在 Symbol.asyncIterator
可写 no
可枚举 no
可配置 no

范例

User-defined Async Iterables

You can define your own async iterable by setting the [Symbol.asyncIterator] property on an object.

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

When creating an API, remember that async iterables are designed to represent something iterable — like a stream of data or a list —, not to completely replace callbacks and events in most situations.

Built-in Async Iterables

There are currently no built-in JavaScript objects that have the [Symbol.asyncIterator] key set by default. However, WHATWG Streams are set to be the first built-in object to be async iterable, with [Symbol.asyncIterator] recently landing in the spec.

规范

规范
ECMAScript (ECMA-262)
The definition of 'Symbol.asyncIterator' in that specification.

浏览器兼容性

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. 更新 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 63 Edge 79 Firefox 57 IE No Opera 50 Safari 11.1 WebView Android 63 Chrome Android 63 Firefox Android No Opera Android 46 Safari iOS No Samsung Internet Android 8.0 nodejs 10.0.0

图例

完整支持

完整支持

不支持

不支持

另请参阅

元数据

  • 最后修改: