我有一个函数返回一个 deferred.promise
- 然而,jQuery 的 deferred
变体 - 但概念相同。
无论文件读取是否成功,我都想进入链的下一部分。类似于以下内容:
var a,
b,
c;
readFile(fileNameA)
.then(
function (res) {
a = res; // res might be null
return readFile(fileNameB);
},
function (err) {
return readFile(fileNameB);
}
)
.then(
function (res) {
b = res; // res might be null
return readFile(fileNameC);
},
function (err) {
return readFile(fileNameC);
}
)
.then(
function (res) {
c = res; // res might be null
callPostLogic();
},
function (err) {
callPostLogic();
}
);
然而,对我来说,这似乎是不必要的代码重复。因为我不想在其中一个读取失败时破坏链条 - 所以在本地处理每个错误。
有没有办法解决这个问题,使其更干净并避免代码重复?我不太关心每个 readFile
调用的粒度。
我只是不喜欢在已解决/拒绝的回调中重复代码调用。
最佳答案
由于您使用的是 jQuery Promises,因此您可以使用函数 deferred.always
。如果成功或失败,它就会被调用。它就像 try-catch
-Block
finally
您可以轻松使用它,例如:
$.get( "test.php" ).always(function() {
alert( "$.get completed with success or error callback arguments" );
});
所以在你的情况下你可以做类似的事情
readFile(fileNameA)
.always(function() {
return readFile(fileNameB);
})
.always(function() {
return readFile(fileNamec);
})
.always(function() {
// finished
});
在这里您可以找到文档:https://api.jquery.com/deferred.always/
关于javascript - promise - 链接解决/拒绝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33673483/