0

In a controller I have multiple calls to some methods that return a promise.

I'm going to use the await/async statement and I have something like this:

try {
  let foo = await myFirstMethod();
  let bar = await mySecondMethod();
}catch(e => {
  // which method fails between the both?
});

Yes, I know that I could split the call in two separate try/catch statement, but I have to handle also this scenario and in addiction I'd like to understand which is the better way to have a specific type of error response for each methods.

Any helps or suggestions are appreciated and welcome.

Thanks

Zauker
  • 2,344
  • 3
  • 27
  • 36
  • 2
    `catch(e => { })` -> `catch(e) { }` – VLAZ Jun 03 '21 at 15:28
  • 1
    It depends on what your first and second method throw. You could distinguish on the error message or you could different concrete error Implementation. – k0pernikus Jun 03 '21 at 15:34
  • Related: https://stackoverflow.com/q/41102060/457268 – k0pernikus Jun 03 '21 at 15:34
  • Possible duplicate of [Correct Try…Catch Syntax Using Async/Await](https://stackoverflow.com/q/44663864/1048572) - or is there something typescript-specific you want to know? – Bergi Jun 03 '21 at 16:31

1 Answers1

0

What you're looking for is Promise.allSettled

let promises = [myFirstMethod() ,mySecondMethod()];

let allResults = Promise.allSettled(promises).then((results) => {
    // results is an array of objects representing the promises' final state
    // result.status is either "fulfilled" or "rejected"

   results.forEach(result => {
       console.log(result.status);
   });

});
code_monk
  • 9,451
  • 2
  • 42
  • 41
  • You forgot to call the methods in your `promises` array creation – Bergi Jun 03 '21 at 16:17
  • 1
    I don't think this is what the OP wants. They were running two async methods sequentially, your code changes this to concurrent execution without good reason. – Bergi Jun 03 '21 at 16:18
  • No, promises are not "invoked". As you say, `Promise.allSettled` accept an array of promises, but you have to call `myFirstMethod()` and `mySecondMethod()` to *create* these promises. – Bergi Jun 03 '21 at 19:09
  • 1
    updated code per @Bergi's note, however, complaints about sequential execution still valid. This is perhaps not the best way to address OP's need – code_monk Jun 04 '21 at 04:10