0

I currently have a node.js/graphql micro service that uses Promise.all to call another micro service via apolloFetch. My Promise.all part seems to be working ok but I'm trying to have the error logging part working. I need to make sure that the Promise.all executes ALL THE PROMISES and not quit after it encounters the first error. Once it executes ALL THE PROMISES, I need to then populate an array meant just errors, which I then loop through and insert into a database using another function. I currently have the array and the catch set up, but when I intentionally generate an error, I don't see the array being populated.

Could someone take a gander if my code is indeed doing what I'm intending it to do?

     const ErrorsArray = [];
     Promise.all(promises.map(p => apolloFetch({p}))).then((result) =>                         

          {
                resolve();
                console.log("success!");
            }).catch((e) => {
                ErrorsArray.push( e );
            });
     if( ErrorsArray && ErrorsArray.length ){
        for(a=0;a<ErrorsArray.length;a++){
          funcLogErrors( ErrorsArray[a].errorCode,         
                         ErrorsArray[a].message );
         //Not sure if these are correct^^^^^^^^^
        }
      }

PS: Also, how do I simulate a mySQL database error without shutting my database down, so I can test this function to make sure all the database errors are being caught as well?

Roger Dodger
  • 927
  • 2
  • 16
  • 37

1 Answers1

1

Your ErrorsArray will always contain at most ONE error. This is because Promise.all either resolve all promises or fail (and reject) after the first error it encounters.

Simply put, there's no need for an array here since there's no scenario where you have multiple exceptions.

If you really want to have a "chain" like logic, you should look into Observables. You can convert your Promises into Observables using rxjs and more specifically with the catchError and switchMap operators

molamk
  • 4,076
  • 1
  • 13
  • 22
  • thanks for that explanation; the problem with using rxjs and such is not an option for me since I'd like to stay away from using additional libs or packages. Is there no other alternative for me to achieve my objective of executing ALL the promises even if there is/are an error/s and then log those errors into an array and subsequently into a database? – Roger Dodger Feb 27 '19 at 21:39
  • 1
    there are other ways, but doing that is an anti-pattern. If you really want to, you can [look here](https://stackoverflow.com/questions/30362733/handling-errors-in-promise-all) – molamk Feb 27 '19 at 21:43