How to correctly trap and read any errors generated in a Promise.all call? [duplicate]

丶灬走出姿态 提交于 2019-12-24 19:27:59

问题


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?


回答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



来源:https://stackoverflow.com/questions/54914590/how-to-correctly-trap-and-read-any-errors-generated-in-a-promise-all-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!