2016-07-08 197 views
6

我目前正试图实现我自己的承诺在Angular 2中使用。如果我reject承诺,我会得到Error: Uncaught (in promise): nope(…),但只有第一个承诺被拒绝。未处理的承诺拒绝当拒绝承诺在角2

这是Angular 2.0.0-rc.4,但我在其他行为中注意到了这一点。我的问题是,这是我对Promise的理解错误,还是应该向Angular项目报告这个错误?

示例代码:

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"); 

控制台(谷歌浏览器51.0.2704.106,Linux的64位):

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(…) 
+1

你使用es6 promise还是你有自己的实现? – Kliment

+0

据我所知,执行是'zone.js'中的'ZoneAwarePromise'。这就是为什么我认为它与Angular有关。 –

+0

标题有点让人误解。 '在Angular 2中实现自己的承诺'明确表明自制Promise实现。 – estus

回答

9

应该

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

p.then(...)独自创建未处理的链,这很麻烦Zone.js.如果你已经处理了蓝鸟的“未处理的拒绝”,你可能已经知道规则。

+0

谢谢,我刚刚发现,当它在我的大脑中“点击”,当我想到为什么解决方案从Thierry Templier工作。 –

3

你可以执行以下操作:

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)); 
+1

其实,这个工作,谢谢,我从来没有想过这个。但为什么使用'.catch'回调是错误的? –

+1

这是因为'catch'是一个承诺处理程序(然后或捕获),他们不停止链接... –