Last active
August 20, 2019 14:38
-
-
Save jfet97/83ca9065d200f2025c5758feafb7c456 to your computer and use it in GitHub Desktop.
PromiseQueueAsyncGen
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
function aitGen() { | |
let i = 1; | |
return { | |
async next() { | |
if(i > 5) return Promise.resolve({ value: void 0, done: true }); | |
const res = await fetch(`https://jsonplaceholder.typicode.com/posts/${i++}`).then(x => x.json()); | |
return Promise.resolve({ value: res, done: false }); | |
} | |
} | |
} | |
const ait = aitGen(); | |
// general time consistency is lost, because e.g. the fifth call could end before the others | |
// but the 'i' state is correctly shared so the fifth call is correctly requesting the element number five to the source | |
// and the last call will correctly receive { done: true } | |
;(async () => { | |
ait.next(); | |
ait.next(); | |
ait.next(); | |
ait.next(); | |
console.log(await ait.next()); // { done: false, value: { userId: 1, id: 5, title: ... } } | |
console.log(await ait.next()); // { done: true, value: undefined } | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment