[英]Making an asynchronous generator *[Symbol.asyncIterator] without async/await but with promises only
[英]What is the best practice to create an async iterator? Should I use an async generator function or rather use Symbol.asyncIterator?
此代碼按預期工作:
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function getAsyncData() {
await sleep(1000); // simulate database/network delay...
return [1, 2, 3, 4, 5]; // ...then return some data
}
const asyncIterable = (async function* filterAsyncData() {
const items = await getAsyncData();
for (const item of items) {
yield item;
}
})();
const asyncIterable2 = {
[Symbol.asyncIterator]() {
return {
values: null,
idx: 0,
async next() {
if (this.values === null) {
this.values = await getAsyncData();
}
if (this.idx < this.values.length) {
this.idx = this.idx + 1;
return Promise.resolve({ value: this.values[this.idx - 1], done: false });
}
return Promise.resolve({ done: true });
}
};
}
};
async function main() {
for await (const filteredItem of asyncIterable) {
console.log(filteredItem);
}
}
main()
如果我在main
function 中使用asyncIterable
或asyncIterable2
則不會,我總是得到相同的結果。 定義我的可迭代對象的最佳實踐是什么? 是否有關於首選哪個選項的指導方針? 為什么?
這與同步迭代器相同:生成器函數比手動實現迭代器 object 更容易編寫,也更容易正確。 僅當您需要一些其他方式無法實現的非標准行為時才執行此操作。 特別是使用異步生成器功能,您甚至可以免費獲得next
調用的正確排隊,這真是令人頭疼(您的asyncIterable2
失敗了 this 1 )。
最常見的可迭代實現是使Symbol.asyncIterator
方法成為異步生成器方法:
const asyncIterable = {
async *[Symbol.asyncIterator]() {
yield* await getAsyncData();
},
};
1: const it = asyncIterable2[Symbol.asyncIterator](); it.next(); it.next()
const it = asyncIterable2[Symbol.asyncIterator](); it.next(); it.next()
const it = asyncIterable2[Symbol.asyncIterator](); it.next(); it.next()
- 中間沒有任何await
- 將調用getAsyncData
兩次,因為this.values == null
在兩個調用中
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.