Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 880
Breedly Avatar asked Jan 29 '16 17:01

Breedly


People also ask

How do you handle rejected promises with await?

You can handle rejected promises without a try block by chaining a catch() handler before awaiting the promise.

How do I resolve async await rejection?

Find out how to reject a Promise in async/await syntax Therefore, you simply need to throw an error inside the async function to make it reject. For example: function wait(ms) { return new Promise((resolve) => setTimeout(resolve, ms)); } async function foo() { await wait(1000); throw new Error('Woops! '); } console.

Does promise reject to catch?

Normally, such . catch doesn't trigger at all. But if any of the promises above rejects (a network problem or invalid json or whatever), then it would catch it.

How do you catch errors with await?

The await keyword before a promise makes JavaScript wait until that promise settles, and then: If it's an error, an exception is generated — same as if throw error were called at that very place. Otherwise, it returns the result.


1 Answers

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.

like image 138
Shanoor Avatar answered Sep 21 '22 09:09

Shanoor