Let me prefix the question with a note that I'm tagging the question with deno and javascript as I'm still getting my head around generator functions, iterators and some other newer async JS features, so I'm not exactly sure if this is more an issue with Deno API, or Javascript.
So, Deno.readDir()
returns an AsyncIterable, and all the examples I've seen process the results with for await loop like so:
for await (const dirEntry of Deno.readDir("/")) {
console.log(dirEntry.name);
}
For await loop is not good for my use case as I need to interleave traversing the directory with another async loop. I'd rather use something like let reader = Deno.readDir("/");
then inside my other asynchronous code, call something like let nextdir = await reader.next();
as needed.
I can't do that, as the result of Deno.readDir("/")
does not implement next();
With pretty much trial and error, guesswork and trying everything under the sun I was able to make it work like this:
let reader = Deno.readDir(source);
let readeriter = reader[Symbol.asyncIterator](); // <-- the weird part
// other code here between...
let nextdir = await readeriter.next(); // works!
The questions is, the above code, specifically the part reader[Symbol.asyncIterator]()
looks so ugly and hacky it can't be how I'm supposed to use that API, or can it? I'm struggling to understand what that line actually does. I get a feeling there must be cleaner way to consume the result of readDir (other than for...await).
I can't understand why readDir result does not directly implement next(), as the result, AsyncIterable is obviously something that is intended to be iterated over. Why is that?
This is not opinion, but an honest question because I'm a bit confused with all this generator-iterator business. Could Deno in theory implement next() right in the AsyncIterable so that one doesn't need to jump through hoops to get it?