如何使用回调转换简单的$ http以使用promises

时间:2014-05-20 19:00:36

标签: javascript angularjs promise

我试图用角度来约束承诺,我有下面的例子,我想转换成使用承诺,所以希望它能帮助我去#A~哈哈! #34;

我在互联网上找到的所有示例都使用服务/工厂/等等,我只是想知道制作简单的最佳方法,比如使用promises。

angular.module('web').controller('CardsCtrl',function($scope, $http, $q){

    // Don't worry about how the variable "users" gets populated, let's just say it came into magical existance from a unicorn's horn.
    $scope.users = users;

    // Loop through all the users
    for(var i = 0; i < $scope.users .length; i++) {

      // THIS FAILS BECAUSE THE LOOP FINISHES BEFORE THE 1ST GET REQUEST FINISHES SO WE CAN'T REFERENCE THE I VARIABLE
      $http.get('http://uifaces.com/api/v1/random', function(face) {
        $scope.users[i].face = face.image_urls.mini;
      });
    }
});

2 个答案:

答案 0 :(得分:4)

你拥有的不是承诺的问题。它只是循环中的经典&#34;闭包&#34;问题。

修复如下:

for(var i = 0; i < $scope.users .length; i++) {
  (function(i) {
    $http.get('http://uifaces.com/api/v1/random', function(face) {
      $scope.users[i].face = face.image_urls.mini;
    });
  }(i));
}

答案 1 :(得分:3)

以下是我的写作方式:

 $q.all($scope.users.map(function(user){
      return $http.get('http://uifaces.com/api/v1/random').then(function(face){
           return user.face = face.image_urls.mini;
      });
 })).then(function(results) {
    // results contains the images actually used, so you can use it here too
 });