Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * @param {any[]} input
- * @param {Function} iterator
- * @param {any} initivalValue
- * @returns {Promise}
- */
- function asyncReduce(input, iterator, initialValue) {
- const arr = input.map(item => item());
- return Promise.all(arr).then(results => {
- let acc = initialValue;
- results.forEach((item, i, arr) => {
- acc = iterator(acc, item);
- });
- return acc;
- });
- }
- const a = () => Promise.resolve('a');
- const b = () => Promise.resolve('b');
- const c = () => new Promise(resolve => setTimeout(() => resolve('c'), 100));
- asyncReduce(
- [a, b, c],
- (acc, curr) => [...acc, curr],
- ['d']
- ).then(results => {
- console.log(results); // ['d', 'a', 'b', 'c'];
- });
Add Comment
Please, Sign In to add comment