Using Async Generators

#7 · closed · 1 comments

View on GitHub ↗

crazy4groovy

Cool lib! Here's an alternative I tweaked by using an async generator API (to keep the internal state without a callback): ``` const { dirname, resolve } = require("path"); const { readdir, stat } = require("fs"); const { promisify } = require("util"); const toStats = promisify(stat); const toRead = promisify(readdir); module.exports = async function* (startDir) { let dir = resolve(".", startDir); let tmp, stats = await toStats(dir); if (!stats.isDirectory()) { dir = dirname(dir); } while (true) { tmp = yield {dir, filenames: await toRead(dir)}; if (tmp) return resolve(dir, tmp); dir = dirname(tmp = dir); if (tmp === dir) break; } }; ``` Can be used like this: ``` const esc = require("./escalade"); (async () => { // A - for-await-of loop let g = esc(__dirname); for await (const { dir, filenames } of g) { console.log(dir, filenames); } // B - .next() g = esc(__dirname); let r = await g.next(); console.log(r); // r.done === false r = await g.next(); console.log(r); // r.done === false r = await g.next("!!!done!!!"); console.log(r.value); // r.done === true })(); ``` Cheers!

Comments

lukeed

Hey, thanks! Haha one of my initial implementation was using an async generator :D I dropped it in favor of what I have though because they're only supported in Node 10+ & `escalade` was made to support existing modules serving Node 8.x (and 6.x via `escalade/sync`. It's not any bigger – and IIRC the current implementation was a bit faster too – so I was happy to go w/ the wider-support route. Thanks though! :)