1

The code below is small function to guaranteed all Backbone.collection / model fetch operation. The only problem that I'm facing right now is deferred.resolve where you can see the Models is actually an array.

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;
} 

The purpose of this is to cater simple for-loop operation whereby each loop has it's own fetch operation.

Example 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);

I am expecting fetchData will return Collection/Model in order of ipid. But result of console will always showing res_ipid not in order because it depends on race condition of fetch.

Hope someone will shed even more light for this.

Nurdin
  • 23,382
  • 43
  • 130
  • 308
Muhaimin
  • 1,643
  • 2
  • 24
  • 48
  • Is `Models` a deferred or promise? It needs to be in order to work with `$.when()` and if it is, then you don't need to make your own deferred as you can just use the one in `Models` and return it. If it's not a deferred, then you will have to hook up some completion action to your deferred. – jfriend00 Jun 04 '14 at 02:55

1 Answers1

0

I think you're making this harder than it needs to be. Instead of:

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);

You should just be able to do:

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);
machineghost
  • 33,529
  • 30
  • 159
  • 234