给定一个 Javascript 生成器函数,该函数从异步生成器源获取数据,并对其进行后处理,例如:
async function* getData() {
let currentPage = 0
while(true) {
let records = await fetch('api/data?page='+currentPage)
if (records.length == 0) return
for (record of records) {
yield record
}
currentPage++
}
}
function* myGenerator() {
let index = 0
let gen = getData()
while(true) {
index++
console.log('Setup', index)
yield gen.next().then(rs => {
console.log('Processing', index)
return rc.value.toLowerCase()
})
}
}
如果它被快速调用多次(比承诺工厂结果更快地解决),
index
值被报告为循环中的最后一个值:
let promises = []
let gen = myGenerator()
for (let i = 0; i < 10; i++) {
promises.push(gen.next().value)
}
结果为“设置 1、设置 2、设置 3、...、设置 10”,然后重复十次“处理 10”。 “设置”调用是有意义的,因为它可以排队多个生成器结果,这些结果都是未决的承诺,然后一旦异步生成器可以使用一页数据,假设数据页中有 10 个或更多项,所有 10的未决承诺将迅速得到解决。但是,为什么它们都报告相同的“10”索引值,而不是 1-10?在这种设置的生成器函数中有没有一种方法可以跟踪当前异步响应是通过生成器的哪个原始调用?