简体   繁体   English

angularJS + express中$ q.all的重复响应承诺

[英]Duplicated response promise with $q.all in angularJS + express

When using $q.all() to get multiple responses, I get the same values in the response object. 当使用$ q.all()获取多个响应时,我在响应对象中获得了相同的值。 I get as many objects back as promises declared, but all the 'name' fields have the same value (the last one, 3). 我得到的对象与承诺的声明一样多,但是所有的“名称”字段都具有相同的值(最后一个为3)。

.controller('myCtrl', function ($scope, $state, $q, myService) {

   $scope.myList = [];

   $scope.create = function() {
      var newObject;
      var promises = [];
      for(var i = 0; i < 4; i++){
        newObject = { name: i };
        promises[i] = myService.create(newObject);
      }
      $q.all(promises).then(
       function (response) {
         $scope.myList = response;
       }
      );
   };
}

And here's my service: 这是我的服务:

    .service('myService', function ($http, $q, baseURL) {

       this.create = function(object) {
         var deferred = $q.defer();
         //console.log shows that object still has the proper 'name' value
         $http.post(url, object).then(
            function (response) {
              // console.log shows that all response objects have the same 'name' value.
              deferred.resolve(response);
            }
          );
         return deferred.promise;
       };
}

Any input is appreciated since it's my first approach to promises in Angular. 感谢任何输入,因为这是我在Angular中实现诺言的第一种方法。

在重新声明变量时,通过在循环内移动newObject声明来解决该问题,promise会将其先前的值保留给自己。

I'm not really sure what it is you are trying to do, but the way you have your code written, it will always end up with the name of the last one because you are over-writing your promise each time. 我不确定自己要做什么,但是您编写代码的方式总是以最后一个的名字结尾,因为您每次都在重写承诺。 You would need to do something similar to the following: 您将需要执行以下操作:

      var newObject;
  var promises = [];
  for(var i = 0; i < 4; i++){
    newObject = { name: i };
    var promise = myService.create(newObject);
   promises.push(promise);
  }
  $q.all(promises).then(
   function (response) {
     $scope.myList = response;
   }
  );

}; };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM