Last active
November 2, 2021 03:31
-
-
Save maraisr/6e13d70b216296ea1ff74287b13a040a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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