0

I just started using Promise in my node app. And I believe that in the code below the loop will break if one of then returns an error, which is rejected.

Is there a way to let the loop finish, skipping the ones with errors. And I still would like all the error notices at the end of the loop.

One more question: Is there a better way to resolve instead of using count++; if(count===items.length) resolve(items)

get_customer_purchase = (items) => {
  return new Promise((resolve, reject)=>{
    let count = 0;
    for (let i in items) {
      get_options(items[i].id).then((options)=>{
        //do some process
         count++; if(count===items.length) resolve (items)
      }).catch((error)=>reject(error))
    }    
  })
}
Sihoon Kim
  • 1,481
  • 2
  • 13
  • 32

1 Answers1

0

You can write like this:

get_customer_purchase = (items) => {
  const promiseArray = items.map((item) => {
    return get_options(item.id)
  })

  return Promise.all(promiseArray)
    .then((optionsResult) => items)
}

Notice that if one get_options will fail, you will receive a single fail:

get_customer_purchase(array)
  .then(items => /** do stuff */ )
  .catch(error => /** one get_options fail */ )

If you want to ignore the errors of some get_options you could simply change:

return get_options(item.id).catch(err => {return null})

and then use a .filter function in optionsResult:

.then((optionsResult) => optionsResult.filter(_ => _!==null))
Manuel Spigolon
  • 11,003
  • 5
  • 50
  • 73