0
我有一個函數返回一個deferred.promise
- 但是jQuery的deferred
s變體 - 但是同樣的概念。承諾 - 鏈接解析/拒絕
無論文件讀取是否成功,我想進入下一部分鏈。像下面這樣:
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
調用的粒度。
我只是不喜歡我必須在解決/拒絕的回調中重複代碼調用。
它的工作原理 - 謝謝:) – keldar