What is the proper way to nest promises?


#1

What is the proper way to nest promises? My data.goals seems to be populated if I look at the model via the Ember Extension but nothing is displayed on my page unless I uncomment the “debugger” line.

return Ember.$.getJSON(url + 'loc/' + id + '?ind=1&stat=2&type=8').then(function(data) {
  Ember.$.getJSON(url + 'mg/goals?aid=' + data.id + '&year=2015', function(goals) {
    data.goals = goals;
  }); 
  // debugger;
  return data;
});

#2

This seems to work.

return Ember.$.getJSON(url + 'loc/' + id + '?ind=1&stat=2&type=8').then(function(data) {
  Ember.$.getJSON(url + 'mg/goals?aid=' + data.id + '&year=2015').the(function(goals) {
    data.goals = goals;
    return data;
  }); 
});

#3

To clarify, the idea behind chaining promises in Ember is that you don’t have to keep indenting. Reformatted for clarity:

return Ember.$.getJSON(url + 'loc/' + id + '?ind=1&stat=2&type=8')
  .then(function(data) {
    return Ember.$.getJSON(url + 'mg/goals?aid=' + data.id + '&year=2015')
  }).then(function(goals){
    data.goals = goals;
    return data;
  }).then(function(data){
    //if data is a promise, you could do something with it here.
  });
});

#4

@kylecoberly That wont work unless you return the second ajax call’s promise


#5

Holy smokes, totally correct. Fixed!