[英]How to return a new promise instead of an error on a failed ajax request in Javascript/Jquery?
我有一個創建deferred
對象的函數。 fail
我正在調用一個回退函數,后者又創建並返回它自己的deferred/promise
對象。 我想返回這個后備 deferred
的結果,但我只能在初始調用時返回error
。
這是我正在做的事情:
// method call
init.fetchConfigurationFile(
storage,
"gadgets",
gadget.getAttribute("data-gadget-id"),
pointer
).then(function(fragment) {
console.log("gotcha");
console.log(fragment);
}).fail(function(error_should_be_fragment) {
console.log("gotcha not");
console.log(error_should_be_fragment);
});
如果我需要的文檔/附件不在localstorage中,我的fetchConfiguration
調用會嘗試從localstorage加載並從文件加載回退。
init.fetchConfigurationFile = function (storage, file, attachment, run) {
return storage.getAttachment({"_id": file, "_attachment": attachment})
.then(function (response) {
return jIO.util.readBlobAsText(response.data);
})
.then(function (answer) {
return run(JSON.parse(answer.target.result))
})
.fail(function (error) {
// PROBLEM
console.log(error);
if (error.status === 404 && error.id === file) {
return init.getFromDisk(storage, file, attachment, run);
}
});
};
我的問題是我可以捕獲404
allright,但我不想返回error
對象,而是返回init.getFromDisk
生成的init.getFromDisk
。
問題 :
是否可以在錯誤處理程序中返回我的getFromDisk
調用的結果? 如果沒有,我將如何構建我的調用,以便我總是向第一個方法調用返回一個承諾?
感謝幫助!
解決方案
謝謝您的幫助! 修正如下:
init.fetchConfigurationFile(
storage,
"gadgets",
gadget.getAttribute("data-gadget-id"),
pointer
).always(function(fragment) {
console.log("gotcha");
console.log(fragment);
});
init.fetchConfigurationFile = function (storage, file, attachment, run) {
return storage.getAttachment({"_id": file, "_attachment": attachment})
.then(function (response) {
return jIO.util.readBlobAsText(response.data);
})
.then(
function (answer) {
return run(JSON.parse(answer.target.result));
},
function (error) {
if (error.status === 404 && error.id === file) {
return init.getFromDisk(storage, file, attachment, run);
}
}
);
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.