Symbol.asyncIterator
Symbol.asyncIterator 靜態資料屬性表示 內建符號 Symbol.asyncIterator。 非同步迭代器協議 會查詢此符號以獲取返回物件非同步迭代器的函式。為了使物件成為非同步可迭代物件,它必須具有 [Symbol.asyncIterator] 鍵。
試一試
const delayedResponses = {
delays: [500, 1300, 3500],
wait(delay) {
return new Promise((resolve) => {
setTimeout(resolve, delay);
});
},
async *[Symbol.asyncIterator]() {
for (const delay of this.delays) {
await this.wait(delay);
yield `Delayed response for ${delay} milliseconds`;
}
},
};
(async () => {
for await (const response of delayedResponses) {
console.log(response);
}
})();
// Expected output: "Delayed response for 500 milliseconds"
// Expected output: "Delayed response for 1300 milliseconds"
// Expected output: "Delayed response for 3500 milliseconds"
值
內建符號 Symbol.asyncIterator。
Symbol.asyncIterator 的屬性特性 | |
|---|---|
| 可寫 | 否 |
| 可列舉 | 否 |
| 可配置 | 否 |
示例
使用者定義的非同步可迭代物件
您可以透過在物件上設定 [Symbol.asyncIterator]() 屬性來定義自己的非同步可迭代物件。
js
const myAsyncIterable = {
async *[Symbol.asyncIterator]() {
yield "hello";
yield "async";
yield "iteration!";
},
};
(async () => {
for await (const x of myAsyncIterable) {
console.log(x);
}
})();
// Logs:
// "hello"
// "async"
// "iteration!"
在建立 API 時,請記住非同步可迭代物件旨在表示可迭代的內容——例如資料流或列表——而不是在大多數情況下完全取代回撥和事件。
內建非同步可迭代物件
核心 JavaScript 語言中沒有非同步可迭代物件。一些 Web API,例如 ReadableStream,預設情況下具有 Symbol.asyncIterator 方法。
規範
| 規範 |
|---|
| ECMAScript® 2026 語言規範 # sec-symbol.asynciterator |
瀏覽器相容性
載入中…