Angular 2链接承诺并传递拒绝

时间:2017-01-11 15:40:06

标签: javascript angular es6-promise

应该是一个简单的问题,但是我找不到关于如何做的文档。

链接这样的承诺:

// Making a promise, no problem
let promise = new Promise((resolve, reject) => {
    let data = {}; // do something
    reject(data);
});

// First chain, no problem
promise.then(data => {
    console.log('Success callback', data); // This will not be called
}).catch(err => {
    console.log('Error callback', err); // This WILL be called
})

// Second chain, acts as resolved
.then(data => {
    console.log('Level 2 success', data); // This WILL be called
}).catch(err => {
    console.log('Level 2 error', err); // This will NOT be called
});

我理解,除非我从第一个catch回调中传递拒绝,否则后续的then将被解决。

那么......如何在catch函数中调用reject?

1 个答案:

答案 0 :(得分:4)

请参阅https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch

您需要在catch处理程序中抛出异常,例如拒绝第二个链。

// First chain, no problem
promise.then(data => {
    console.log('Success callback', data); // This will not be called
}).catch(err => {
    console.log('Error callback', err); // This will NOT be called
    throw "zonk";
})