简体   繁体   中英

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. I get as many objects back as promises declared, but all the 'name' fields have the same value (the last one, 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.

在重新声明变量时,通过在循环内移动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;
   }
  );

};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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