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.
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
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 |
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.
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. |
| Desktop | Mobile | Server | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
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 |
完整支持
不支持
Symbol
Function
Object
Object.prototype.__defineGetter__()
Object.prototype.__defineSetter__()
Object.prototype.__lookupGetter__()
Object.prototype.__lookupSetter__()
Object.prototype.hasOwnProperty()
Object.prototype.isPrototypeOf()
Object.prototype.propertyIsEnumerable()
Object.prototype.toLocaleString()
Object.prototype.toSource()
Object.prototype.toString()
Object.prototype.valueOf()
Object.setPrototypeOf()