Skip to content

Instantly share code, notes, and snippets.

@dotproto
Last active April 26, 2018 21:17
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 dotproto/7233e905e047df780403380ed354047a to your computer and use it in GitHub Desktop.
Save dotproto/7233e905e047df780403380ed354047a to your computer and use it in GitHub Desktop.
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