我正在使用backbone来获取模型+ jquery promise 以确保它已被获取。
我调用这个函数
rippleidcollection.createIdList(param).then // do some stuff
当 fetch 触发成功时,此方法效果很好,但当触发错误时,上述函数的 then 部分不会执行(这是一个问题,因为我想随后触发错误消息)。
以下是createdIdList函数的代码:
createIdList: function(toresolves) {
var self = this;
var xhrs = _.map(toresolves, function(toresolve,i) {
var id = toresolve.id;
var model = new RippleId({id:id}, address);
var xhr = model.fetch({
success: function(model,response) {
self.add(model);
},
error: function(model, response) {
self.add(model);
}
});
return xhr;
});
var sync = $.when.apply(null, xhrs);
return sync;
}
因此,当(model.fetch)成功时,rippleidcollection.createIdList(param).then//do some stuff 会执行传递负载,但不会在触发错误时执行。我想要的只是错误负载也被传递,这样我就可以管理错误消息...e'etc
我认为我错过了一些有关 promise 的基本内容,但我不确定是什么。感谢您的帮助!
最佳答案
then
采用第二个参数来处理错误:
rippleidcollection.createIdList(param).then(function(result){
// stuff to do on success
}, function(err){
// deal with error case, your code for handling errors goes here.
});
请考虑更改您的后端,以获取 ID 列表并批量添加它们 - 这样会更加高效,并且发出的请求也会少得多。
关于jquery promise 在ajax调用错误时返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34116287/