Middle
/** * Implement the sumPromises function, which takes * promises as arguments and returns the sum * of their results. * * The function can accept any number of arguments. * Any promise APIs can be used. */ // Usage example const promise1 = Promise.resolve(1); const promise2 = Promise.resolve(2); sumPromises(promise1, promise2).then(console.log); // 3
sobes.tech AI
Answer from AI
The sumPromises function should accept any number of promises, wait for their completion, and return the sum of their results. To do this, it is convenient to use Promise.all, which takes an array of promises and returns a promise with an array of results.
Example implementation:
function sumPromises(...promises) {
return Promise.all(promises)
.then(results => results.reduce((acc, val) => acc + val, 0));
}
// Example usage
const promise1 = Promise.resolve(1);
const promise2 = Promise.resolve(2);
sumPromises(promise1, promise2).then(console.log); // 3
Thus, we gather all results and sum them.