Why await not right working with reject error

Viewed 111

Why promise catch not working with await?

I want catch error when rejected, but I got two differences result

(async () => {
    var t = (new Promise((r1, r2) => r2(12345))); 
    t.catch(e=> console.log(e)); 
    await t; 
})()

Results in error: VM5989:1 Uncaught (in promise)

(async () => {
    var t = (new Promise((r1, r2) => r2(12345))).catch(e=> console.log(e));
    await t; 
})()

Causes no error and returns 12345

demo image:

at node@12 / chrome@75 console , I got the two differences result.

when I use t.catch, I got Unhandled promise rejection.

when I use (new Promise()).catch, I got except result.

why? And how I can use t and get the right result?

2 Answers

In the first example, you create a new promise that handles the exception by calling t.catch(), but you don't assign it to t, so t remains a promise with an unhandled rejection.

In the second example, t references the chain which is a promise with a handled rejection (the .catch() continuation does not throw so it resolves with undefined), so awaiting t will not cause the async function to throw.

However, because t in the first example still contains a rejected promise, awaiting it will cause the async function to throw.

In the first case, since Promise is asynchronous in nature and statement r2 was already executed even before attaching the catch.

That means catch was not present when r2 - reject function - was called.

Whenever you reject while using promise then catch must be present. Otherwise, it's obvious to see an error on reject.

Edit: As answered by @Patrick Roberts,

the error is not due to unhandled catch but because of the awating for rejected t. While in the case of the second statement t (promise) was still pending.

Related