[英]How to return a new promise instead of an error on a failed ajax request in Javascript/Jquery?
I have a function which creates a deferred
object. 我有一个创建
deferred
对象的函数。 On fail
I'm calling a fallback function, which in turn creates and returns it's own deferred/promise
object. fail
我正在调用一个回退函数,后者又创建并返回它自己的deferred/promise
对象。 I would like to return the result of this fallback- deferred
but I'm only able to return the error
on my initial call. 我想返回这个后备
deferred
的结果,但我只能在初始调用时返回error
。
Here is what I'm doing: 这是我正在做的事情:
// 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);
});
My fetchConfiguration
call tries to load from localstorage and falls back to loading from file if the document/attachment I need is not in localstorage. 如果我需要的文档/附件不在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);
}
});
};
My problem is I can catch the 404
allright, but instead of returning the error
object, I would like to return the promise generated by init.getFromDisk
. 我的问题是我可以捕获
404
allright,但我不想返回error
对象,而是返回init.getFromDisk
生成的init.getFromDisk
。
Question : 问题 :
Is it possible to return the result of my getFromDisk
call in the error handler? 是否可以在错误处理程序中返回我的
getFromDisk
调用的结果? If not, how would I have to structure my calls so that I'm always returning a promise to my first method call? 如果没有,我将如何构建我的调用,以便我总是向第一个方法调用返回一个承诺?
Thanks for help! 感谢帮助!
SOLUTION : 解决方案
Thanks for the help! 谢谢您的帮助! Fixed it like this:
修正如下:
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.