Skip to content

Instantly share code, notes, and snippets.

@jfet97
Last active August 20, 2019 14:38
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 jfet97/83ca9065d200f2025c5758feafb7c456 to your computer and use it in GitHub Desktop.
Save jfet97/83ca9065d200f2025c5758feafb7c456 to your computer and use it in GitHub Desktop.
PromiseQueueAsyncGen
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