Peter Prographo
Peter Prographo

Reputation: 1331

How to resolve promise making function in map chain?

I'd like all the slowAdd()s in the code below to happen in parallel, but I don't want to do the next .map() step until they are all resolved. How to do it?

async function slowAdd(a) {
  return new Promise( (resolve,reject) => setTimeout(() => resolve(a+5), 1000) )
}

async function calcArray(list) {
  return list
    .map( a => a+1 )
    .map( a => slowAdd(a) )
    .map( a => a+1 )
}

async function main() {
  const list = [1, 2, 3, 4, 5]
  const newList = await calcArray(list)
  console.log(newList)
}

main()
  .catch(err => {
    console.error(err);
  })
  .then(() => process.exit());

Upvotes: 0

Views: 137

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370729

Put it in a Promise.all, and then you'll need another .map inside a .then for the subsequent action:

async function slowAdd(a) {
  return new Promise( (resolve,reject) => setTimeout(() => resolve(a+5), 1000) )
}

async function calcArray(list) {
  return Promise.all(
    list
      .map( a => a+1 )
      .map( a => slowAdd(a) )
  )
    .then(addedResults => addedResults.map( a => a+1 ));
}

async function main() {
  const list = [1, 2, 3, 4, 5]
  const newList = await calcArray(list)
  console.log(newList)
}

main()

Upvotes: 2

Related Questions