from: Accept a callback function.

This commit is contained in:
David Braun 2017-10-21 15:31:59 -04:00
parent 8c26f23ead
commit 6b577ea6cd
No known key found for this signature in database
GPG key ID: 5694EEC4D129BDCF
3 changed files with 38 additions and 14 deletions

View file

@ -308,30 +308,44 @@ const Channel = function(length = 0) {
Channel.from = values => {
const channel = Channel();
(async () => {
// iterable
try {
// iterable
for (let value of values) {
await channel.push(value);
}
await channel.close();
} catch (exception) {
// Assume it's a Node.js stream.readable.
// callback function
try {
for (;;) {
const value = values();
values.on("readable", async () => {
while (true) {
const data = values.read();
if (data === null) {
if (value === undefined) {
await channel.close();
break;
} else {
await channel.push(data);
await channel.push(value);
}
}
});
} catch (exception) {
// Node.js stream.readable
values.on("readable", async () => {
while (true) {
const data = values.read();
values.once("end", channel.close);
if (data === null) {
break;
} else {
await channel.push(data);
}
}
});
values.once("end", channel.close);
}
}
})();