Skip to content

Instantly share code, notes, and snippets.

@getify getify/1.js
Last active Jun 8, 2019

Embed
What would you like to do?
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);
});
}
@bcdbuddy

This comment has been minimized.

Copy link

commented Jun 7, 2019

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
You can’t perform that action at this time.