【发布时间】:2017-03-27 02:14:21
【问题描述】:
有了 Promise,我们可以使用 .then 的变体在发生错误时拆分链。这是一个使用fetch的示例
fetch('http://website.com').then(
// Perform some logic
(response) => response.json().then(({ answer }) => `Your answer: ${answer}`),
// Skip json parsing when an error occurs
(error) => 'An error occurred :(',
).then(console.log);
这让我可以跳过响应处理逻辑,只响应原始 fetch 语句中出现的错误。 RxJS 中的类似内容可能如下所示:
Observable.fromPromise(fetch('http://website.com'))
// if I put .catch here, the result will be piped into flatMap and map
.flatMap(response => response.json())
.map(({ answer }) => `Your answer: ${answer}`)
// if I put .catch here, errors thrown in flatMap and map will also be caught
.subscribe(console.log);
作为处于代码状态的 cmets,我不能简单地放入一个 catch 运算符,因为它的行为与我的 Promise 链不同。
我知道我可以通过涉及实现的自定义运算符来获得它,或者将捕获可观察到的错误与此合并,但这一切似乎都是相当大的矫枉过正。有没有一种简单的方法来实现承诺链的行为?
【问题讨论】:
标签: javascript promise rxjs rxjs5