So I’m trying to use jQuery’s deferred (and the fact that $.ajax returns a promise) to handle some asynchronous code.
Here’s a quick example which shows what’s happening
var update_model = function(model, resp){
model.set('id', resp.id);
m = model;
};
var print_id = function(){
console.log(m.get('id'));
};
var MyModel = Backbone.Model.extend({});
var m = new MyModel({title: 'test'});
var model_promise = m.save({author: 'me'}, {success: update_model});
$.when(model_promise).then(print_id);
The problem is that print_id is being called BEFORE update_model and I’m not sure how to make it happen the other way around.
In the actual example, I’m trying to save anywhere from 1 to 100 models, and I need to get the IDs from those models before I can move onto the next step.
Am I missing something basic here?
EDIT
update_model does get called — it just happens after print_id. Also, I’ve tried using the done method on model_promise and then using then:
model_promise.done(update_model).then(print_id);
But then update_model doesn’t receive it’s necessary arguments.
The problem is that your deferred resolves in the success method. To use deferreds w/the ajax methods use the the
deferred.done().then()pattern (check out the “The jqXHR Object” section here: http://api.jquery.com/jQuery.ajax/).