AsyncIterator.prototype[Symbol.asyncIterator]()
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since January 2020.
AsyncIterator
实例的 [Symbol.asyncIterator]()
方法实现了异步可迭代协议并允许内置的异步迭代器被大多数期望异步迭代器的语法所接受,如 for await...of
循环。它返回 this
的值,即异步迭代器对象本身。
尝试一下
const map1 = new Map();
map1.set("0", "foo");
map1.set(1, "bar");
const iterator1 = map1[Symbol.iterator]();
for (const item of iterator1) {
console.log(item);
}
// Expected output: Array ["0", "foo"]
// Expected output: Array [1, "bar"]
语法
js
asyncIterator[Symbol.asyncIterator]()
参数
无。
返回值
this
的值,即异步迭代器对象本身。
示例
使用 for await...of 循环进行迭代
请注意,你很少需要直接调用该方法。[Symbol.asyncIterator]()
方法的存在使得所有内置的异步迭代器都成为异步可迭代对象,而像 for await...of
循环这样的迭代语法会自动调用该方法来获取异步迭代器来进行循环。
js
const asyncIterator = (async function* () {
yield 1;
yield 2;
yield 3;
})();
(async () => {
for await (const value of asyncIterator) {
console.log(value);
}
})();
// 输出:1,2,3
规范
Specification |
---|
ECMAScript® 2025 Language Specification # sec-asynciteratorprototype-asynciterator |
浏览器兼容性
Report problems with this compatibility data on GitHubdesktop | mobile | server | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
[Symbol.asyncIterator] |
Legend
Tip: you can click/tap on a cell for more information.
- Full support
- Full support
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.