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