Executes an array of promises concurrently and returns the aggregated result.
Takes an array of functions or promises and returns a promise that resolves with a concatenated result.
npm run import -- "run all promises sequentially"
function runAllPromises(promises) {
return promises.reduce((promise, func) => {
return promise.then(result => {
return (typeof func == 'function'
? (new Promise(func)) : Promise.resolve(func))
.then(Array.prototype.concat.bind(result));
});
}, Promise.resolve([]));
}
module.exports.runAllPromises = runAllPromises;
/**
* Run an array of promises, allowing each promise to return an array
* that the next promise's callback can concatenate to.
*
* @param {Array} promises - An array of promise-returning functions or promises.
* @returns {Promise} A promise that resolves to the concatenated arrays.
*/
function runAllPromises(promises) {
// Check if input is an array
if (!Array.isArray(promises)) {
throw new Error('Input must be an array of promise-returning functions or promises.');
}
// Use `reduce` to chain the promises together
return promises.reduce((previousPromise, currentPromise) => {
// Check if the current promise is a function or a promise
if (typeof currentPromise!== 'function' &&!(currentPromise instanceof Promise)) {
throw new Error('Each promise must be a function or a promise.');
}
// If the current promise is a function, wrap it in a new promise
const currentPromiseWrapped = typeof currentPromise === 'function'
? new Promise(currentPromise)
: Promise.resolve(currentPromise);
// Use `then` to concatenate the result of the current promise to the previous result
return previousPromise.then(result => currentPromiseWrapped.then(array => array.concat(result)));
}, Promise.resolve([])); // Initialize with an empty array
}
module.exports.runAllPromises = runAllPromises;
runAllPromises
Executes an array of promises concurrently, aggregating results.
promises
(Array): An array of functions or promises to be executed.Promise
: A promise that resolves with the aggregated result of all promises.This function uses reduce
to execute each promise in the promises
array concurrently. For each promise, it extracts the result, applies the next function (if any), and concatenates the result with the output of the previous promise. If a promise is a non-function value, it is treated as resolved and returned as is.
const promises = [
() => Promise.resolve('A'),
() => Promise.resolve('B'),
() => Promise.resolve('C')
];
runAllPromises(promises).then(result => console.log(result)); // Output: ["A", "B", "C"]