Skip to content

Instantly share code, notes, and snippets.

@maraisr
Last active November 2, 2021 03:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maraisr/6e13d70b216296ea1ff74287b13a040a to your computer and use it in GitHub Desktop.
Save maraisr/6e13d70b216296ea1ff74287b13a040a to your computer and use it in GitHub Desktop.
function makePromisibleStream(streamable) {
return {
async then(resolve) {
const stream = streamable();
const returns = [];
for await (const i of stream) {
returns.push(i);
}
resolve(returns);
},
[Symbol.asyncIterator]() {
return streamable();
},
subscribe(cb) {
const stream = streamable();
async function loop(value) {
const v = await value;
if (v.done) return;
cb(v.value);
loop(stream.next());
}
loop(stream.next());
return () => {
stream.return();
};
},
};
}
async function* get_data() {
yield await Promise.resolve("a");
yield await Promise.resolve("b");
yield await Promise.resolve("c");
}
const test = makePromisibleStream(get_data);
console.log("promise", await test);
for await (const i of test) {
console.log("loop", i);
}
test.subscribe(value => {
console.log("sub", value);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment