我希望确认没有遗漏的技巧;在Kris Kowal的库中,您可以将以下代码作为Promise中通用的异常处理语句:
var a, b, c, d, e, f;
readFile('fileA')
.then(function (res) {
a = res;
return readFile('fileB');
})
.then(function (res) {
b = res;
return readFile('fileC');
})
.then(function (res) {
c = res;
return readFile('fileD');
})
.then(function (res) {
d = res;
return readFile('fileE');
})
.then(function (res) {
e = res;
return readFile('fileF');
})
.then(function () {
f = res;
})
.catch(function () {
// error happened in file read *somewhere* (don't care where)
});
在jQuery的延迟对象中,没有
catch
语句,相反,我必须这样做:var a, b, c, d, e, f;
readFile('fileA')
.then(function (res) {
a = res;
return readFile('fileB');
})
.fail(function () {
// error happened in file read *somewhere* (don't care where)
})
.then(function (res) {
b = res;
return readFile('fileC');
})
.fail(function () {
// error happened in file read *somewhere* (don't care where)
})
.then(function (res) {
c = res;
return readFile('fileD');
})
.fail(function () {
// error happened in file read *somewhere* (don't care where)
})
.then(function (res) {
d = res;
return readFile('fileE');
})
.fail(function () {
// error happened in file read *somewhere* (don't care where)
})
.then(function (res) {
e = res;
return readFile('fileF');
})
.fail(function () {
// error happened in file read *somewhere* (don't care where)
})
.then(function (res) {
f = res;
return readFile('fileF');
})
.fail(function () {
// error happened in file read *somewhere* (don't care where)
});
很遗憾,每个then
分支都有独特的逻辑。我是否漏掉了什么,或者上面jQuery版本是实现Kris Kowal的q
库等效的唯一方法?
then()
并在最后使用单个.fail();
吗?这应该可以解决问题。 - T J.fail()
方法不会捕获异常,也不能被强制执行。在调用fail()
后,所在的链路会确保一直沿着错误路径执行。与此相反的是,.then()
方法的错误处理器并不会自动捕获异常,但可以通过返回一个resolved promise来实现;如果返回其它任何东西,都会更改沿着错误路径传递的“失败原因”。 - Roamer-1888