Waiting for the response of several promises in EmberJS

时间:2016-04-04 18:53:29

标签: ember.js promise rsvp.js

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?

3 个答案:

答案 0 :(得分:3)

返回一个承诺并在解决所有内部承诺后解决它。我没有试过代码,但这应该指出你如何继续。

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

答案 1 :(得分:0)

实际上,除非你在路线的模型钩子中,否则你不能等待承诺。 请参阅the guide

上的模型挂钩

您还有其他选择,尝试在解析数据时直接将数据设置为项目。 (在然后功能内)

答案 2 :(得分:0)

您可以尝试这样的事情:

return Promise.all(parameters.map(parameter => Ember.$.ajax(url).then(response => {
    'name': parameter.get('displayName'),
    'color': parameter.get('color'),
    'type': chart.get('chartType'),
    'turboThreshold': 0,
    'data': response.data
}))).then(data => {
    console.log(data);
    return data;
});