Created
December 20, 2017 15:51
-
-
Save jooyunghan/d33d302a076a750eeabe0a6713e087a1 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 createAsyncIterator() { | |
const promises = []; | |
const values = []; | |
let done = false; | |
const subscription = this.subscribe({ | |
next(value) { | |
if (promises.length > 0) { | |
promises.shift().resolve({ value, done: false }); | |
} else { | |
values.push(value); | |
} | |
}, | |
complete() { | |
done = true; | |
promises.splice(0).forEach(p => p.resolve({ done })); | |
} | |
}); | |
return { | |
next() { | |
if (values.length > 0) { | |
return { value: values.shift(), done: false }; | |
} | |
if (done) { | |
return { done }; | |
} | |
return new Promise((resolve, reject) => { | |
promises.push({ resolve, reject }); | |
}); | |
}, | |
return() { | |
subscription.unsubscribe(); | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment