jQuery Deferred - catch vs fail
jQuery Deferred - catch vs fail
我想确保我没有错过任何技巧;在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
库中实现等效功能的唯一方法?
假设readFile
返回一个promise对象,您实际上可以使用$.when()
异步加载所有文件(如果您不关心文件的读取顺序,则为):
来自文档:
在将多个Deferred对象传递给jQuery.when()的情况下,该方法从一个新的"主"Deferred object返回Promise,该对象跟踪已传递的所有Deferred的聚合状态。一旦所有Deferred都被解析,该方法就会解析其主Deferred,或者一旦其中一个Deferred被拒绝,就会拒绝主Deferred。如果解析了主机Deferred,则会执行主机Deferrd的doneCallbacks。传递给doneCallbacks的参数为每个Deferred提供解析的值,并与Deferred传递给jQuery.when()的顺序相匹配
(强调矿)
$.when(readFile('fileA'), readFile('fileB'), readFile('fileC'), readFile('fileD'), readFile('fileE'), readFile('fileF'))
.then(function(a, b, c, d, e, f) {
// big success
},function() {
// error happened in file read *somewhere* (don't care where)
});
相关文章:
- setInteval vs setTimeout
- $(this).prop('property') vs. this.property
- Js.erb VS按钮标记-不'不起作用.为什么?
- reactjs this.refs vs document.getElementById
- Performance: NaCl vs Emscripten
- 文本表示法VS.构造函数,用于在JavaScript中创建对象
- Advantages to DOMParser vs template & innerHTML
- JavaScript-===vs===运算符性能
- 开发第三方小部件-Angular vs jQuery vs普通的旧JS
- PhantomJS(vs nightwatch.js)设置cookie错误
- Javascript events: window.event vs argument reference (funct
- ExtJS 4 Object.prototype fail
- 需要确认我对Servlet vs RESTful网页的理解's的差异
- "#"keyCode=222 vs 51(Chrome与Android版Chrome)-为什么有区别
- .notion vs.[]notation |插入到文本对象中
- Javascript-使用“”将toDateStringMonth从文本字符串解析为数字字符串;如果“;vs“;开关”;
- 没有框架/DLL的VS Web应用程序项目
- Eval vs execscript
- VS代码:在<脚本>标签
- jQuery Deferred - catch vs fail