【问题标题】:Unhandled Promise rejection when rejecting Promise in Angular 2 [duplicate]在Angular 2中拒绝Promise时未处理的Promise拒绝[重复]
【发布时间】:2016-11-10 23:33:39
【问题描述】:

我目前正在尝试实现我自己的 Promise,以便在 Angular 2 中使用。如果我 reject 承诺,我将获得 Error: Uncaught (in promise): nope(…),但仅限于第一个被拒绝的 Promise。

Angular 2.0.0-rc.4,但我在其他行为中注意到了这一点。我的问题是,这是我对 Promises 理解的错误,还是应该向 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");

控制台(Google Chrome 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(…)

【问题讨论】:

  • 你是使用 es6 promise 还是有自己的实现?
  • 据我所知,实现是来自zone.jsZoneAwarePromise。这就是为什么我认为它与 Angular 有关。
  • 标题有点误导。 “在 Angular 2 中实现自己的 Promise”明确表明有自制的 Promise 实现。

标签: angular promise


【解决方案1】:

您可以:

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

【讨论】:

  • 其实,这行得通,谢谢,我从来没想过。但是为什么使用.catch回调是错误的呢?
  • 这是因为catch 是一个承诺处理程序(then 或 catch)并且它们不会停止链接......
【解决方案2】:

应该是

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

p.then(...) 单独创建未处理的链,这困扰着 Zone.js。如果您处理过 Bluebird 的“未处理的拒绝”,您可能已经知道规则了。

【讨论】:

  • 谢谢,当我思考 Thierry Templier 的解决方案为何奏效时,我才发现它在我的大脑中发出“咔哒”声。
猜你喜欢
  • 1970-01-01
  • 2018-03-19
  • 1970-01-01
  • 1970-01-01
  • 2015-04-26
  • 2018-08-26
  • 2017-11-20
  • 2019-04-15
  • 1970-01-01
相关资源
最近更新 更多