Skip to content

Instantly share code, notes, and snippets.

@dotproto dotproto/merge.js
Last active Apr 26, 2018

Embed
What would you like to do?
Merge async iterators
(async function() {
console.clear();
class Deferred {
constructor() {
this.promise = new Promise((resolve, reject) => {
this.resolve = resolve;
this.reject = reject;
});
}
}
function wait(time) {
return new Promise(resolve => setTimeout(resolve, time));
}
// ---
async function* asyncCounter(time = 1000, maxIterations = 3) {
let count = 0;
while (count < maxIterations) {
await wait(time);
console.log('counter', count);
yield count++;
}
}
// ---
const merge = (collection) => {
let nextValue = new Deferred();
const it = collection[Symbol.asyncIterator]();
return {
[Symbol.asyncIterator]() {
return this;
},
// Synchronously proxy the iterator
async next() {
console.log('before');
it.next().then(val => {
const currentValue = nextValue;
nextValue = new Deferred();
currentValue.resolve(val)
});
return nextValue.promise;
}
}
};
for await (const a of merge(asyncCounter(0))) {
console.log('MAIN', a);
}
})().then(()=> console.log('async complete'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.