gpt4 book ai didi

javascript - jQuery Deferred - 捕获与失败

转载 作者:行者123 更新时间:2023-11-29 10:37:33 28 4
gpt4 key购买 nike

我想确保我没有漏掉一个把戏;在 Kris Kowal 的库中,您可以将以下内容作为 promises 中的通用 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() 异步加载所有文件(当然,如果您不关心文件的读取顺序):

来自文档:

In the case where multiple Deferred objects are passed to jQuery.when(), the method returns the Promise from a new "master" Deferred object that tracks the aggregate state of all the Deferreds it has been passed. The method will resolve its master Deferred as soon as all the Deferreds resolve, or reject the master Deferred as soon as one of the Deferreds is rejected. If the master Deferred is resolved, the doneCallbacks for the master Deferred are executed. The arguments passed to the doneCallbacks provide the resolved values for each of the Deferreds, and matches the order the Deferreds were passed to 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)
});

关于javascript - jQuery Deferred - 捕获与失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34318801/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com