I want to do something like this
const { Readable } = require("stream");
function generatorToStream(generator) {
return new Readable({
read() {
(async () => {
for await (const result of generator()) {
if (result.done) {
this.push(null);
} else {
this.push(result.value);
}
}
})();
}
});
}
generatorToStream(async function*() {
const msg1 = await new Promise(resolve =>
setTimeout(() => resolve("ola amigao"), 2000)
);
yield msg1;
const msg2 = await new Promise(resolve =>
setTimeout(() => resolve("ola amigao"), 2000)
);
yield msg2;
const msg3 = await new Promise(resolve =>
setTimeout(() => resolve("ola amigao"), 2000)
);
yield msg3;
}).pipe(process.stdout);
but it's not working, the end event has never been called and i haven't received any data on my terminal.
Any solution or tips on how to implement it?
.catch(console.error)
to your IIAFE. – Plantresult
won't be an iteration record when you are usingfor await of
, but the value itself. When the generator is done, the loop just ends. – Plantasync function
withawait
called separately for each Promise is just like a generator. Is it even possible to combine them? – Strang