Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unhandled Promise rejection when rejecting Promise in Angular 2 [duplicate]

I am currently trying to implement my own Promise to be used inside Angular 2. If I reject the promise, I'll get an Error: Uncaught (in promise): nope(…), but only on the first Promise to be rejected.

It's Angular 2.0.0-rc.4, but I noticed this in other behaviors. My question is, is this an error in my understanding of Promises, or is this a bug that should be reported to the Angular project?

Sample code:

import {Component} from '@angular/core';
import {bootstrap} from '@angular/platform-browser-dynamic'
@Component({
    template: "TestComponent"
})
class TestComponent {
}
bootstrap(TestComponent, []);

let p = new Promise((resolve, reject) => {
    console.log("create promise");
    reject("nope");
});
console.log("setting up");
p.then(r => console.log("then: " + r));
p.catch(e => console.log("reject: " + e));
console.log("setup done");

Console (Google Chrome 51.0.2704.106, Linux 64 bit):

create promise
setting up
setup done
reject: nope
Angular 2 is running in the development mode. Call enableProdMode() to enable the production mode.
Unhandled Promise rejection: nope ; Zone: <root> ; Task: Promise.then ; Value: nope
Error: Uncaught (in promise): nope(…)
like image 211
Martin C. Avatar asked Jul 08 '16 11:07

Martin C.


People also ask

How do you handle unhandled Promise rejections?

If an error condition arises inside a promise, you “reject” the promise by calling the reject() function with an error. To handle a promise rejection, you pass a callback to the catch() function. This is a simple example, so catching the rejection is trivial.

What causes unhandled Promise rejection?

UnhandledPromiseRejectionWarning originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with . catch().

How do you terminate the node process in unhandled Promise rejection?

To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1) (node:12367) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated.

Does reject return a 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 .


1 Answers

It should be

p
.then(r => console.log("then: " + r))
.catch(e => console.log("reject: " + e));

p.then(...) alone creates unhandled chain, this bothers Zone.js. If you have dealt with Bluebird's 'unhandled rejections', you may already know the rules.

like image 125
Estus Flask Avatar answered Sep 30 '22 19:09

Estus Flask