Symbol.asyncIterator - JavaScript 编辑

The 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.

Description

The 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.

Property attributes of Symbol.asyncIterator
Writableno
Enumerableno
Configurableno

Examples

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.

Specifications

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

Browser compatibility

BCD tables only load in the browser

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:144 次

字数:3520

最后编辑:7 年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文