我想知道如果可能的话,如何覆盖自定义迭代器的next()
方法。例如,我有一个返回迭代器的函数:
function myFunction(...args) {
return {
async next() {
// Lazy!
const id = await resource.getId(...args)
console.log('first')
// After first call, overwrite the next!
this.next = async () => {
console.log('second')
// with id, do other thing
const value = await resource2.getOtherThing(id)
if (value.property) return { done: false, value }
return { done: true, value }
}
return this.next()
}
[Symbol.asyncIterator] {
return this
}
}
}
但这并没有被覆盖,因为first
出现在每个循环中:
for await (const x of myFunction(...) {
console.log(x)
}
提前谢谢。