Skip to content

Instantly share code, notes, and snippets.

@getify
Last active June 8, 2019 08:17
Show Gist options
  • Save getify/838afe7ec6118cc619094ff5816e0c31 to your computer and use it in GitHub Desktop.
Save getify/838afe7ec6118cc619094ff5816e0c31 to your computer and use it in GitHub Desktop.
race-promises-pool
async function racePromisesPool([ ...prs ] = []) {
var raceWon = false;
var prListeners = prs.map(function listen(pr,idx){
return pr.then(function t(v){
if (!raceWon) {
raceWon = true;
prs.splice(idx,1); // remove the promise from the pool since it won the race
return v;
}
});
});
return [ prs, await Promise.race(prListeners) ];
}
main();
// *******************************************
async function main() {
// pull file responses ASAP and print them out as they arrive
for await (let text of loadFiles([
"https://url.tld/file1",
"https://url.tld/file2",
"https://url.tld/file3"
])) {
console.log(text);
}
}
async function *loadFiles(files) {
var pool = files.map(getFile);
while (pool.length > 0) {
// get the next-ready promise from the pool
let nextResponse;
[ pool, nextResponse ] = await racePromisesPool(pool);
// push response out through iterator
yield nextResponse;
}
}
function getFile(file) {
return new Promise(function c(resolve){
ajax(file,resolve);
});
}
@babacarcissedia
Copy link

Hello @getify,
dope!
How useful this could be in a project ? I still don't see any use case for it

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment