Guest User

Untitled

a guest
Dec 11th, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.67 KB | None | 0 0
  1. /**
  2. * @param {any[]} input
  3. * @param {Function} iterator
  4. * @param {any} initivalValue
  5. * @returns {Promise}
  6. */
  7. function asyncReduce(input, iterator, initialValue) {
  8. const arr = input.map(item => item());
  9.  
  10. return Promise.all(arr).then(results => {
  11. let acc = initialValue;
  12.  
  13. results.forEach((item, i, arr) => {
  14. acc = iterator(acc, item);
  15. });
  16.  
  17. return acc;
  18. });
  19. }
  20.  
  21. const a = () => Promise.resolve('a');
  22. const b = () => Promise.resolve('b');
  23. const c = () => new Promise(resolve => setTimeout(() => resolve('c'), 100));
  24.  
  25. asyncReduce(
  26. [a, b, c],
  27. (acc, curr) => [...acc, curr],
  28. ['d']
  29. ).then(results => {
  30. console.log(results); // ['d', 'a', 'b', 'c'];
  31. });
Add Comment
Please, Sign In to add comment