Why Symbol.asyncIterator is not working?
const obj = {
async *[Symbol.asyncIterator] () {
yield 10;
yield 100;
yield 1000;
},
};
for (const val of obj) {
console.log(obj);
}
error: TypeError: obj is not iterable
for await (const val of obj) {
console.log(obj);
}
error: SyntaxError: for await (... of...) is only valid in async functions and async generators
(async() => {
for await (const val of obj) {
console.log(val);
}
})()
error: SyntaxError: for await (... of...) is only valid in async functions and async generators
Because it's an async iterable, you need to await each value:
for await (const val of obj) {
console.log(obj);
}
NOTE: this all needs to be wrapped in an async function because Node.js doesn't support top-level await by default:
(async() => {
for await (const val of obj) {
console.log(val);
}
})()
Use await in an async function
const obj = { async * [Symbol.asyncIterator]() { yield 10; yield 100; yield 1000; }, }; (async() => { for await (const val of obj) { console.log(val); } })()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.