Angular Looping Promises - 函数返回空对象

时间:2017-04-26 19:42:31

标签: angular angular-promise

我试图将一个结果(数组)从一个promise传递给一个迭代这个结果的函数,为每个项目发出一个get请求,并在返回之前用结果创建一个新对象。问题是在解析promise之前返回对象并填充它。从多个承诺中返回填充对象的正确方法是什么?

Class D{

@Autowire
private B b;

// How can I get the value of A which is set in C
//something like

A a= b.getA();

}

2 个答案:

答案 0 :(得分:2)

您应该考虑使用$q.all这样的情况,您可以在单个承诺数组中收集所有承诺,然后将其传递到$q.all&返回结果承诺。在所有承诺完成后,它将确保您返回data

在您的代码中,您只是执行异步ajax调用而不必担心它们是否已完成。在此之后,您将返回detailedPackages数据。但很明显它会是空的。

<强>代码

function getPackageDetails(packages) {
  var detailedPackages = {};
  var promises = []; //promise array
  angular.forEach(packages, function(p) {

    var promise = vsmsPackageFactory.getPackage(p.id)
    .then(function(response) {
      var subsystem = response.data.packageManifest.subsystem;
      var partNumber = response.data.packageManifest.resultConfig.partNumber;
      var packageName = response.data.packageMetaData.packageName;
      if(detailedPackages[subsystem] === undefined) {
        detailedPackages[subsystem] = {};
      }
      if(detailedPackages[subsystem][partNumber] === undefined) {
        detailedPackages[subsystem][partNumber] = {};
      }
      detailedPackages[subsystem][partNumber][packageName] = response.data;
    });
    promises.push(promise);
  });
  return $q.all(promises).then(function(){
    return detailedPackages;  // returned data after all promises are done
  });
}

答案 1 :(得分:1)

这可以使用promise all here来实现。

 var promises = [];
 promises.push(new Promise(function (resolve, reject) {
   vsmsPackageFactory.getPackage(p.id)
    .then(function(response) {
     ...
     resolve('If you want to return something')
    });
 });
 //After the loop it's finished you execute your promises
 Promise.all(promises).then(function (values) {
  ... perform more code
 });