0

const array = [1, 2, 3]

const wrapper = (task) => {
 return new Promise((resolve, reject) => {
  setTimeout(() => {
   if(task !== 1) {
    console.log('Rejected task -', task)
    reject(task)
   }
   else {
    console.log('Resolved task -', task)
    resolve(task)
   }
  }, 1000 * task)
 })
}
const main = async() => {
 try{
  await Promise.all(array.map(async task => 
    wrapper(task)
  ))
 } catch(e){
  console.log('Main function catch error from task -', e)
 }
}

main()

Following this code, just task1 will be resolved and for other task2 and task3, these will be rejected with task number. But at main function, rejection will be caught once.

Current Output:

Resolved task - 1
Rejected task - 2
Main function catch error from task - 2
Rejected task - 3

Expect Output:

Resolved task - 1
Rejected task - 2
Main function catch error from task - 2
Rejected task - 3
Main function catch error from task - 3

Is there anyway to catch all the rejection? Using for loop is not a solution. Since it will run the task asynchronously but I'd like to run the tasks synchronously like multiple threading.

tpikachu
  • 4,478
  • 2
  • 17
  • 42
  • Especially have a look at [this answer](https://stackoverflow.com/a/56255129/906113). – str Jan 07 '20 at 14:02
  • Just move the `catch` inside the `map` loop, so that you're able to catch all errors individually? – Bergi Jan 07 '20 at 14:48

0 Answers0