From d04bfbcdeacf75bdc9e14b97d385a173819a3461 Mon Sep 17 00:00:00 2001 From: Andrew Rumble Date: Thu, 6 Mar 2025 16:08:43 +0000 Subject: [PATCH] Add promiseMapSettledWithLimit utility GitOrigin-RevId: e34102de17f28e43deb383d630088c6e753e2ec1 --- libraries/promise-utils/index.js | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/libraries/promise-utils/index.js b/libraries/promise-utils/index.js index c71b17127b..557210ae26 100644 --- a/libraries/promise-utils/index.js +++ b/libraries/promise-utils/index.js @@ -13,6 +13,7 @@ module.exports = { expressify, expressifyErrorHandler, promiseMapWithLimit, + promiseMapSettledWithLimit, } /** @@ -264,3 +265,19 @@ async function promiseMapWithLimit(concurrency, array, fn) { const limit = pLimit(concurrency) return await Promise.all(array.map(x => limit(() => fn(x)))) } + +/** + * Map values in `array` with the async function `fn` + * + * Limit the number of unresolved promises to `concurrency`. + * + * @template T, U + * @param {number} concurrency + * @param {Array} array + * @param {(T) => Promise} fn + * @return {Promise>>} + */ +function promiseMapSettledWithLimit(concurrency, array, fn) { + const limit = pLimit(concurrency) + return Promise.allSettled(array.map(x => limit(() => fn(x)))) +}