简体   繁体   中英

async/await catch rejected Promises

I'm just getting started with async/await and running into a problem.

I can do as expected:

async function x() {
  let y = await Promise.resolve(42);
  return y;
}

But when I reject a Promise :

async function bad() {
  try {
   await Promise.reject('bad');
  } catch(err) {
    err; //AssertionError: TypeError: (0 , _errorHandler2.default) is not a function
  }
}

How do I catch rejected Promises with async/await ?

What bad; alone is supposed to do? The error is caught as expected, you just don't do anything with it:

async function bad() {
  try {
    await Promise.reject('bad');
  } catch(err) {
    console.log(err);
  }
}

bad();

This outputs bad as expected. Code here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM