Javascript – UnhandledPromiseRejectionWarning on async await promise

javascriptnode.js

UnhandledPromiseRejectionWarning on async await promise

I have this code:

function foo() {
  return new Promise((resolve, reject) => {
    db.foo.findOne({}, (err, docs) => {
      if (err || !docs) return reject();
      return resolve();
    });
  });
}

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

foobar();

Which results with:

(node:14843) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): false

(node:14843) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Note: I know I can solve this issue like this:

foo().then(() => {}).catch(() => {});

But then we are "back" to callbacks async style.

How do we solve this issue?

Best Answer

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)
  }
}
Related Topic