1

async function thisThrows() {
  return new Promise((resove, reject) => {
    throw new Error("Thrown from thisThrows()");
  });
}

async function thatThrows() {
  return new Promise(async(resolve, reject) => {
    try {
      await thisThrows();
    } catch (err) {
      throw err;
    }
    console.log('reached here');
    resolve(true);
  });
}

async function run() {
  try {
    await thatThrows();
  } catch (e) {
    console.error('catch error', e);
  } finally {
    console.log('We do cleanup here');
  }
}

run();

I have situation where i don't want the statement console.log('reached here'); resolve(true); should execute if error in thrown by previous statements. I tried several combinations but no luck. run method should catch the error. In my above code run method catch method not executed

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
Sushant Prasad
  • 122
  • 1
  • 10
  • Do not use `new Promise` in `thatThrows`. It's never rejected. – Bergi Nov 11 '20 at 09:21
  • @Bergi After removing as per your suggestion, I see console statement "reached here". – Sushant Prasad Nov 11 '20 at 10:17
  • `async function thatThrows() { await thisThrows(); console.log('reached here'); }` will not log "reached here" if `thisThrows` actually throws (returns a rejected promise). – Bergi Nov 11 '20 at 10:21
  • Notice that also `thisThrows` should be either `function thisThrows() { return new Promise((resove, reject) => { reject(new Error("…")); }); }` or just `async function thisThrows() { throw new Error("…"); }` – Bergi Nov 11 '20 at 10:22
  • @Bergi, I executed the code but the problem is neither run method **catch** nor **finally** block gets executed. I need to get executed either of these statement – Sushant Prasad Nov 11 '20 at 10:31
  • Then you're not running the code from my comments but still the broken one that doesn't settle the `new Promise` in case of an error. – Bergi Nov 11 '20 at 10:39
  • @Bergi Please find the jsfiddle link [here](https://jsfiddle.net/cebsushant/65ojLx0f/1/) – Sushant Prasad Nov 11 '20 at 11:10
  • If possible could you please send me the working code. – Sushant Prasad Nov 11 '20 at 11:11
  • That's the original broken code from your question, which does not run for the reasons explained in the duplicate. Understand the explanation, then fix your code as I outlined in the comments. – Bergi Nov 11 '20 at 11:11

0 Answers0