0

In the following code

// file: main.js
    class A {
    
        async start() {
            
            throw 'error';
        }
    }
    
    module.exports = A;



// file index.js

    var r = require('./main.js'); 
    
    let v = new r();
    
    try {
        v.start(); // error is caught when I use r.start() though
    } catch (e) {
        console.error(e);
    }

I am new to Javascript and Node.js, Node.js throws UnhandledPromiseRejection when I am clearly catching the exception, why does it happen ?

Ajay Sabarish
  • 61
  • 1
  • 7
  • 1
    An `async` function always returns a promise which is **asynchronous**. Suggest you do some research into how to catch promise errors – charlietfl Feb 15 '21 at 13:53
  • @charlietfl thanks for pointing it out, I added await and it worked, but just curious it works without await when I directly invoke it without creating an instance, why ?For ref, see the edited code – Ajay Sabarish Feb 15 '21 at 14:30

2 Answers2

0

This error originated either by throwing inside of an async function without a catch block

To see the reason:

node --trace-warnings index.js

ManuelMB
  • 1,254
  • 2
  • 8
  • 16
0

Your code doesn't work, because you have to await for v.start()

This will work:

class A {
  async start() {
    throw 'error';
  }
}


(async() => {
  let v = new A();

  try {
    await v.start();
  } catch (e) {
    console.error(e);
  }
})()

But this won't

class A {
  async start() {
    throw 'error';
  }
}


(async() => {
  let v = new A();

  try {
    v.start();
  } catch (e) {
    console.error(e);
  }
})()
Konrad
  • 21,590
  • 4
  • 28
  • 64