const fs = require('fs')
async function main () {
const iterator = fs.createReadStream(__filename)[Symbol.asyncIterator]()
for await (const chunk of iterator) {
console.log('got a chunk', chunk.toString())
}
}
main()
I get the error:
(node:13875) UnhandledPromiseRejectionWarning: TypeError: iterator is not async iterable
This isn't exactly a bug, but I think the iterator returned by fs.createReadStream(__filename)[Symbol.asyncIterator]() doesn't implement the iterable protocol which is why this is happening.
It is not possible to know reflectively whether a particular object implements the iterator protocol, however it is easy to create an object that satisfies both the iterator and iterable protocols (as shown in the example below). Doing so allows an iterator to be consumed by the various syntaxes expecting iterables. Thus it is rarely desireable to implement the iterator protocol without also implementing iterable.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterator_protocol
This might be useful if you wanted to consume the first X chunks of a stream using await iterator.next() and then conditionally consume the rest with for await of.
I get the error:
This isn't exactly a bug, but I think the iterator returned by
fs.createReadStream(__filename)[Symbol.asyncIterator]()
doesn't implement the iterable protocol which is why this is happening.This might be useful if you wanted to consume the first X chunks of a stream using
await iterator.next()
and then conditionally consume the rest withfor await of
.