Zen
Zen

Reputation: 5490

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.

Upvotes: 11

Views: 11052

Answers (3)

DMaster
DMaster

Reputation: 641

Without a promise reject handler, chrome would throws reason of the rejection asynchronously that doesn't effects any JavaScript process, just prints the reason to console. If you get annoyed with this, you need to add handler, e.g. Promise.reject(reason).catch(reason => {}).

UPDATE: Why is an error? It may be because rejection is conventionally considered as an exception (an error).

P.S. Your "question" look like a feedback rather than a question. I personally prefer getting the reason as an error.

Upvotes: 3

christophetd
christophetd

Reputation: 3874

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

Upvotes: 2

dark_ruby
dark_ruby

Reputation: 7866

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

Upvotes: 5

Related Questions