[英]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.