【发布时间】:2016-03-22 23:44:53
【问题描述】:
我想确保我没有错过任何技巧;在 Kris Kowal 的库中,您可以在 Promise 中作为通用 catch 语句执行以下操作:
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();?它应该可以工作。 -
这是 Sebastien 的典型问题,我仍然不确定是否可以将 catch 替换为失败
-
@A.Wolff 啊.. 谁塞巴斯蒂安..?另一只狼..? ._.
-
@keldar,部分问题是 jQuery 在 Promises/A+ 标准化之前添加了 Deferreds(我的理解是,大部分标准化是在开发人员学习使用类似 Promise 的行为之后进行的jQuery 的延迟)。幸运的是jQuery 3 will be Promises/A+ compatible。
-
简而言之,jQuery 的
.fail()不能捕捉也不能被捕捉。在fail()之后,链保证保持在其错误路径上。另一方面,.then()的错误处理程序不会自动捕获,但可以通过返回已解决的承诺来实现;返回除了已解决的承诺之外的任何内容都会改变沿错误路径传播的“失败原因”。
标签: javascript jquery promise jquery-deferred deferred