lundi 26 janvier 2015

ensuring that a value is set in api request with promise

I do not think I am using promises correctly in the apiRequest function below. As you can see, the function apiRequest gets triggered by a click of a button. I assumed that the clickToTrigger function would block until the apiRequest has finished and todos has been set, however, I sometimes get error message that todos is undefined in code that runs later on in clickToTrigger function. Is it possible that I have written the promise incorrectly. How should I write the apiRequest to ensure that the code (not displayed) in clickToTrigger won't run until the todos are set?



apiRequest: function(){
var that = this;
var datasource = 'http://ift.tt/1C9qqUT';
return new Ember.$.ajax({url: datasource, dataType: "json", type: 'GET'}).then(function(data){
that.set('todos', data);
});
},


actions: {
clickToTrigger: function(){
this.apiRequest();
todo = this.store.createRecord('index', {
todos: this.get('todos'),
});
todo.save();
//code moves on to do other things that need the todos but they are undefined...
}
},




Aucun commentaire:

Enregistrer un commentaire