Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why it is an error to ignore a rejected promise on Chrome?

I don't want to do anything if the promise is rejected, like getPromise().then(foo=>{});. Why is it an error on Chrome?

(new Promise((resolve, reject)=>{reject()}))
Promise {[[PromiseStatus]]: "rejected", [[PromiseValue]]: undefined}
VM3250:2 Uncaught (in promise) undefined

On Node and Firefox, it is OK to ignore the rejected part.

like image 389
Zen Avatar asked Apr 09 '16 12:04

Zen


People also ask

What happens if Promise is rejected?

If the Promise rejects, the second function in your first . then() will get called with the rejected value, and whatever value it returns will become a new resolved Promise which passes into the first function of your second then. Catch is never called here either.

Is Promise reject an error?

Description. The static Promise. reject function returns a Promise that is rejected. For debugging purposes and selective error catching, it is useful to make reason an instanceof Error .

How do you handle rejection promises?

We must always add a catch() , otherwise promises will silently fail. In this case, if thePromise is rejected, the execution jumps directly to the catch() method. You can add the catch() method in the middle of two then() methods, but you will not be able to break the chain when something bad happens.

What happens if Promise is not resolved or rejected?

So failing to resolve or reject a promise just fails to ever change the state from "pending" to anything else. This doesn't cause any fundamental problem in Javascript because a promise is just a regular Javascript object.


2 Answers

Rejecting a promise basically means something bad happened, and that you should be handling it with a call to catch. If you reject a promise without having a catch, it will throw an exception (more accurately, an unhandled rejection)

var a = (new Promise((resolve, reject) => {
    reject("my error")
})).catch((err) => {
    console.error(err)
})

I'm guessing it is a specificity of V8 if this happens only under Chrome, but it makes sense to me

like image 59
christophetd Avatar answered Sep 23 '22 08:09

christophetd


Promise rejection is like uncaught exception. if you want to ignore exception - catch it, but don't handle, same here - add .catch statement, but do nothing

Promise.reject(new Error('bad..')).catch(e => {})

I would not however recommend that, as promises reject for a reason, so you might want to add some sort of handling logic

like image 34
dark_ruby Avatar answered Sep 26 '22 08:09

dark_ruby