UnhandledPromiseRejectionWarning on async await promise

then(() => {}).catch(() => {}) isn't needed because catch doesn't necessarily should go after then.

UnhandledPromiseRejectionWarning means that a promise weren't synchronously chained with catch, this resulted in unhandled rejection.

In async..await, errors should be caught with try..catch:

async function foobar() {
  try {
    await foo() ? console.log("Have foo") : console.log("Not have foo");
  } catch (error) {
    console.error(error);
  }
}

The alternative is to handle errors at top level. If foobar is application entry point and isn't supposed to be chained anywhere else, it's:

foobar().catch(console.error);

The problem with foo is that it doesn't provide meaningful errors. It preferably should be:

if (err || !docs) return reject(err);

Also, most popular callback-based libraries have promise counterparts to avoid new Promise. It mongoist for mongojs.


Wrap your code in try-catch block.

async function foobar() {
  try {
    await foo() ? console.log("Have foo") : console.log("Not have foo");
  }
  catch(e) {
    console.log('Catch an error: ', e)
  }
}