【发布时间】:2016-07-19 06:38:57
【问题描述】:
我正在尝试从 MDN documentation 中理解 Promise。第一个示例演示了then 和catch 方法:
// We define what to do when the promise is resolved/fulfilled with the then() call,
// and the catch() method defines what to do if the promise is rejected.
p1.then(
// Log the fulfillment value
function(val) {
log.insertAdjacentHTML('beforeend', val +
') Promise fulfilled (<small>Async code terminated</small>)<br/>');
})
.catch(
// Log the rejection reason
function(reason) {
console.log('Handle rejected promise ('+reason+') here.');
});
文档指出then 方法返回一个新的承诺,所以上面的代码不应该等同于
var p2 = p1.then(
// Log the fulfillment value
function(val) {
log.insertAdjacentHTML('beforeend', val +
') Promise fulfilled (<small>Async code terminated</small>)<br/>');
});
p2.catch(
// Log the rejection reason
function(reason) {
console.log('Handle rejected promise ('+reason+') here.');
});
?
如果是这样,那是否意味着只有当从p1.then 返回的承诺而不是承诺p1 被拒绝时才会调用catch 回调?我不需要这样做吗:
p1.then( /* etc. */ );
// and for rejected resolutions
p1.catch( /* etc. */ );
捕捉对承诺 p1 的拒绝,而不是将 catch 链接到 then?
起初,我认为从p1.then 返回的承诺与p1 相同,就像 jQuery 对其大部分 API 所做的那样。但是下面清楚地表明这两个promise是不同的。
var p1 = new Promise(function(resolve, reject) {
resolve("Success!");
});
console.log(p1);
// Promise { <state>: "fulfilled", <value>: "Success!" }
var p2 = p1.then(function(value) {
console.log(value);
});
// Success!
console.log(p2);
// Promise { <state>: "fulfilled", <value>: undefined }
另外,我在 JSFiddle 中使用了三种方法:
p1.then(onFulfilled).catch(onRejected);p1.then(onFulfilled); p1.catch(onRejected);p1.then(onFulfilled, onRejected);
这三个都有效。我可以理解后两者。我的问题的要点是,为什么第一种方法也有效?
【问题讨论】:
-
一个可能的错误会通过 Promise 链传播,直到找到合适的处理程序。因此,即使 p2 承诺与 p1 不同,p1 中的任何错误(拒绝)都会传播到 p2,除非 p1 有单独的
catch()。 -
将
.catch(onRejected)视为.then(null, onRejected)(因为在早期的promise 实现中,基本上就是这样——你理解了后两个,你应该很好地理解第一个 -
@JaromandaX:仍然是,不确定您所说的“早期承诺实施”是什么意思。
-
@bergi ...
.catch在我阅读的第一个 Promises 规范中甚至没有提到,以至于我早期使用 Promise 经常使用.then(null, onError)类型代码(我的记忆虽然可能会感到困惑) -
@JaromandaX:当然,但从它被引入的角度来看(可能是here),它是
then(null, onRejected)的别名
标签: javascript promise chaining