Created
February 15, 2024 14:56
-
-
Save andrew8088/7ecdf23aab7412fe9c702f8ca0387768 to your computer and use it in GitHub Desktop.
Managing Promise Concurrency in JavaScript
This file contains 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
function mapPromises(args, callback, concurrency = 3) { | |
const { promise, resolve } = Promise.withResolvers(); | |
const results = []; | |
let cursor = 0; | |
function next() { | |
if (cursor < args.length) { | |
const index = cursor++; | |
void callback(...args[index]).then(value => { | |
results[index] = { status: 'fulfilled', value }; | |
}).catch(reason => { | |
results[index] = { status: 'rejecte', reason }; | |
}).then(() => { | |
setImmediate(next); | |
}); | |
} else if (args.length === results.length) { | |
resolve(results); | |
} else { | |
// no args remaining, but pending promises - just wait | |
} | |
} | |
while (concurrency--) { | |
next(); | |
} | |
return promise; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
promise withResolvers FTW!