kel*_*dar 5 javascript jquery promise deferred jquery-deferred
我想确保我没有错过任何一个技巧;在 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)
});
Run Code Online (Sandbox Code Playgroud)
在 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)
});
Run Code Online (Sandbox Code Playgroud)
不幸的是,每个then
分支都有独特的逻辑。我是否遗漏了一些东西,或者上面的 jQuery 变体是在 Kris Kowal 的库中实现等效功能的唯一方法q
?
假设readFile
返回一个 Promise 对象,您实际上可以使用异步加载所有文件$.when()
(当然,如果您不关心文件读取的顺序):
来自文档:
在将多个 Deferred 对象传递给 jQuery.when() 的情况下,该方法从新的“主”Deferred 对象返回 Promise,该对象跟踪已传递的所有 Deferred 的聚合状态。一旦所有 Deferred 解析,该方法将解析其主 Deferred,或者一旦其中一个 Deferred 被拒绝,该方法将拒绝主 Deferred。如果主 Deferred 已解析,则执行主 Deferred 的 didCallbacks。传递给 didCallbacks 的参数提供每个 Deferreds 的解析值,并与 Deferreds 传递给 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)
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5848 次 |
最近记录: |