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.
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.
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 |
|
|---|---|
| Writable | no |
| Enumerable | no |
| Configurable | no |
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
| Desktop | Mobile | Server | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
asyncIterator | Chrome Full support 63 | Edge Full support 79 | 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
