I'm trying to make 3 API calls and then return an array of all the data. However, the console.log() (and therefore the function return) is empty as it's not waiting for the AJAX call to be resolved - but I can't do it in the loop as I need all the data.
let data = [];
parameters.forEach((parameter, index) => {
return Ember.$.ajax(url).then((response) => {
data.push({
name: parameter.get('displayName'),
color: parameter.get('color'),
type: chart.get('chartType'),
turboThreshold: 0,
data: response.data
});
});
});
console.log(data);
return data;
I think that I can use Ember.RSVP.hash() for this but I can't seem to get it to work... can anyone point me in the right direction?
Return a promise and resolve it when all of the inner promises are resolved. I didn't try out the code, But this should point you how to proceed.
return new Ember.RSVP.Promise(function (resolve) { //return a promise
let promises = [];
let data = [];
parameters.forEach((parameter, index) => {
promises[index] = Ember.$.ajax(url).then((response) => { //store all inner promises
data.push({
name: parameter.get('displayName'),
color: parameter.get('color'),
type: chart.get('chartType'),
turboThreshold: 0,
data: response.data
});
});
});
Ember.RSVP.all(promises).then(function(){
resolve(data); //resolve the promise when all inner promises are resolved
});
});