-
-
Save getify/838afe7ec6118cc619094ff5816e0c31 to your computer and use it in GitHub Desktop.
race-promises-pool
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
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) ]; | |
} |
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
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); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello @getify,
dope!
How useful this could be in a project ? I still don't see any use case for it