iterate Promises as they resolve

node v10.17.0
version: 1.0.0
endpointsharetweet
async function* g() { yield 1 yield 2 yield 3 } for await (const i of g()) { console.log(i) }
async function* asResolved(promises) { const table = new Map(promises.map(promise => [ /* key= */promise, /* value= */promise.then(value => [promise, value]) ])) while (table.size > 0) { // A rejection will throw here. const [winner, value] = await Promise.race(table.values()) table.delete(winner) yield value } }
const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms)) const delayed = (ms, x) => sleep(ms).then(() => x) promises = [delayed(200, 2), delayed(300, 3), delayed(100, 1)] for await (const value of asResolved(promises)) { console.log(value) }
Loading…

no comments

    sign in to comment