【发布时间】:2013-10-15 17:19:44
【问题描述】:
我有一个创建deferred 对象的函数。在fail 上,我正在调用一个回退函数,该函数反过来创建并返回它自己的deferred/promise 对象。我想返回这个 fallback-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);
});
我的fetchConfiguration 调用尝试从本地存储加载,如果我需要的文档/附件不在本地存储中,则回退到从文件加载。
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 好吧,但是我不想返回error 对象,而是返回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);
}
}
);
};
【问题讨论】:
-
为什么是
.then(...).then()?尝试删除第一个.then()并将第二个.then()的第一个回调更改为function (response) { var answer = jIO.util.readBlobAsText(response.data); return run(JSON.parse(answer.target.result)); }。净效应应该是相同的。 -
同意。目前它只适用于
then().then(),因为我使用的插件需要这种语法。我已经向作者(同事)提过一个then()会让事情变得更容易。 -
好的,
.then().then()可以正常工作,但简化为.then()会更易读(我相信你已经知道了)。
标签: javascript jquery ajax promise jquery-deferred