0

I have an aysnc function that fetches data and returns the value of Promise.all i.e.

const fetchDownloadMenuData = async selectedItems => {
return Promise.all(
  selectedItems.map(async item => {
    try {
      if (item.id === 'interviewGuide') {
        const interviewGuide = await positionCandidatesService.getCandidate(
          positionId,
          candidateSelected.id
        );
        return interviewGuide.interviewGuide;
      }

      if (item.id !== 'overview' && item.id !== 'profile') {
        const outcome = await outcomesService.get(candidateSelected.id, item.id);
        return outcome;
      }
      return null;
    } catch (err) {
      appInsights.trackException({
        error: new Error(`Error fetching candidate outcome: ${JSON.stringify(err)}`)
      });
      return null;
    }
  })
  )};

I call this function like this:

 try {
  downloadData = await fetchDownloadMenuData(selectedItems);
} catch (err) {
  appInsights.trackException({
    error: new Error(`Could not fetch all PDF data: ${JSON.stringify(err)}`)
  });
  return;
}

But it never goes into the catch. Why is this? How do i get it to reject if all the promises don't resolve?

Thanks

Sarun UK
  • 6,210
  • 7
  • 23
  • 48
Paul
  • 219
  • 1
  • 3
  • 11
  • I believe in your catch, you should reject the Promise like so: ```Promise.reject()``` Otherwise it will resolve it – szczocik Nov 17 '20 at 11:34

1 Answers1

0

You're not rejecting in the map...catch block, instead you're returning the null. That's why Promise.all not able to catch the exception. You need use throw in the catch block, Remember, throw will terminate the execution flow.

Try like this

selectedItems.map(async item => {
    try {
       ...async stuff
    } catch (err) {
      appInsights.trackException({
        error: new Error(`Error fetching candidate outcome: ${JSON.stringify(err)}`)
      });
      throw err OR throw new Error(err) <-- this is missing earlier.
    }
  })
Naren
  • 4,152
  • 3
  • 17
  • 28