Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 140071

How to use reduce in a Promise.all instead of map

$
0
0

How can I use reduce in the place of map when using Promise.all? My attempt results in an error UnhandledPromiseRejectionWarning: TypeError: #<Promise> is not iterable at Function.all (<anonymous>)

Eventually I would like to conditionally add innerResult to memo but I need to use reduce first.

const _ = require('lodash');

const eq = [{id:1}, {id:2}, {id:3}];

// block to replace
var biggerEq = _.map(eq, async (e) => {
  const innerResult = await wait(e.id);
  return innerResult;
})

// attempt at replacing above block
// var biggerEq = _.reduce(eq, async (memo, e) => {
//   const innerResult = await wait(e.id);
//   memo.push(innerResult)
//   return memo;
// }, []);

Promise.all(biggerEq).then((result) => {
  console.log(result) // outputs [ 2, 4, 6 ]
})


function wait (id) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(id  * 2);
    }, 1000);
  })
}

Viewing all articles
Browse latest Browse all 140071

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>