Hay una biblioteca llamada p-limit que está diseñada para este propósito, pero está escrita en ESM, por lo que es una molestia. Pensé, ¿qué tan difícil podría ser implementar el mío? Así que se me ocurrió esta implementación:
(async() => { const promisedAxiosPosts = _.range(0, 100).map(async(item, index) => { console.log(`${index}: starting`); return Promise.resolve(); }); let i = 0; for (const promisedAxiosPostGroup of _.chunk(promisedAxiosPosts, 10)) { console.log(`*********************** GROUP ${i} SIZE ${promisedAxiosPostGroup.length} ***********************`); await Promise.all(promisedAxiosPostGroup); i++; } } )().catch((e) => { throw e; }) <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>¿Por qué no está esperando a que se complete cada fragmento antes de pasar al siguiente?
Creo que ese map podría ser el culpable, pero no veo cómo: devuelve Promise<void>[] ; si está await en las funciones, ¿no estaría devolviendo un void[] (no estoy seguro de si eso es algo)?
Para que esto funcione, debe devolver una función que devuelva una promesa cuando se le llame. La función (un thunk ) retrasa la ejecución de la acción real.
Después de fragmentar la matriz, llame a las funciones en el fragmento actual y use Promise.all() para esperar a que se resuelvan todas las promesas:
(async() => { const pendingPosts = _.range(0, 100).map((item, index) => { return () => { // the thunk console.log(`${index}: starting`); // a simulation of the action - an api call for example return new Promise(resolve => { setTimeout(() => resolve(), index * 300); }); } }); let i = 0; for (const pendingChunk of _.chunk(pendingPosts, 10)) { console.log(`*********************** GROUP ${i} SIZE ${pendingChunk.length} ***********************`); await Promise.all(pendingChunk.map(p => p())); // invoke the thunk to call the action i++; } } )().catch((e) => { throw e; }) .as-console-wrapper { max-height: 100% !important; top: 0; } <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>