9

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(…)
Martin C.
  • 12,140
  • 7
  • 40
  • 52
  • 2
    are you using es6 promise or you have your own implementation? – Kliment Jul 08 '16 at 12:04
  • The implementation is `ZoneAwarePromise` from `zone.js`, as far as I can tell. That's why I think it's related to Angular. – Martin C. Jul 08 '16 at 12:14
  • The title is somehow misleading. 'implementing own Promise in Angular 2' unambiguously suggests that there is homebrew Promise implementation. – Estus Flask Jul 08 '16 at 12:27

2 Answers2

13

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.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565
  • Thanks, I just found that out when it made "click" in my brain when I was thinking about why the solution from Thierry Templier worked. – Martin C. Jul 08 '16 at 12:33
3

You could the following:

let p = new Promise((resolve, reject) => {
  console.log("create promise");
  reject("nope");
});
console.log("setting up");
p.then(r => console.log("then: " + r), // <-----
   e => console.log("reject: " + e));
Thierry Templier
  • 198,364
  • 44
  • 396
  • 360