下面的代码是保证所有主干的小函数。收集/模型获取操作。我现在面临的唯一问题是deferred.resolve
你可以看到Models
实际上是一个数组
fetchData: function(Models) {
var deferred = $.Deferred();
var xhr = $.when.apply(this, Models).done(function(data, textStatus, jqXHR) {
deferred.resolve(Models, data, textStatus, jqXHR);
}).fail(deferred.reject);
var promise = deferred.promise();
//promise.abort = _.bind(xhr.abort, xhr);
return promise;
}
这样做的目的是为了满足简单的for循环操作,每个循环都有自己的fetch操作。
示例call fetchData
:
var param = = [{
ipid: 44,
measure: "cumec"
}, {
ipid: 45,
measure: "meter"
}, {
ipid: 46,
measure: "milimeter"
} {
ipid: 47,
measure: "cumec"
}];
var ajax_calls = [];
var _this = this;
var complete = _.after(param.length, function() {
_this.fetchData(ajax_calls).done(performanotherfunction);
});
_.each(param, function(value, key) {
var data = new Collection();
data.id = value.ipid;
ajax_calls.push(data.fetch({
success: function(model) {
console.log(model.get('res_ipid'));
}
}));
complete()
}, this);
我预计fetchData
将按照ipid
的顺序返回Collection/Model。但是控制台的结果总是显示res_ipid
not in order,因为这取决于fetch的竞争条件。
我觉得你把事情复杂化了。而不是:
var complete = _.after(param.length, function() {
_this.fetchData(ajax_calls).done(performanotherfunction);
});
_.each(param, function(value, key) {
var data = new Collection();
data.id = value.ipid;
ajax_calls.push(data.fetch({
success: function(model) {
console.log(model.get('res_ipid'));
}
}));
complete()
}, this);
你应该能够这样做:
var promises = _.map(param, function(value, key) {
var data = new Collection();
data.id = value.ipid;
return data.fetch({
success: function(model) {
console.log(model.get('res_ipid'));
}
});
});
$.when.apply($, promises).done(performanotherfunction);