如何加载用户列表并并行渲染?

时间:2014-12-11 08:06:10

标签: javascript angularjs parallel-processing

在angularjs应用程序中,我有一个用户ID列表,想要并行检索它们,然后在页面上显示它们,但我不知道该怎么做。

我现在的代码看起来像:

<ul ng-controller="MyCtrl">
  <li ng-repeat="user in users">User id: {{user.id}}, name: {{user.name}}</li>
</ul>

app.controller("MyCtrl", function($scope, $http) {
    $scope.userIds = [1,2,3,4, ... to 100];
    $scope.users = [];
    $scope.userIds.each(function(id) {
       $http.get("/users/"+id)
         .success(function(data) {
            // data is a json, like:
            // {
            //    id: ???,
            //    name: ???
            // }
            // 
            $scope.users.append(data);
         });
    })

})

您可以看到逐个检索用户,订单可能会受到干扰。如果Angular有更好的方法吗?

2 个答案:

答案 0 :(得分:0)

你可以使用一系列承诺来实现:

    var promises = [];

    $scope.userIds = [111,222,333,444, ... to 100];
    $scope.users = [];

    for(var i = 0 ; i < $scope.userIds.length ; i++){

        var deffered  = $q.defer();
        var userId = $scope.userIds[i]; 

        $http.get("/users/"+userId).
        success(function(data){
            $scope.users.append(data);
            deffered.resolve(data);
        }).
        error(function(error){
            deffered.reject();
        });

        promises.push(deffered.promise);
    }

    return $q.all(promises).then(function(){
        //here will be code, that should run when all users loaded
    });

答案 1 :(得分:0)

我不知道angularjs,但我认为你可以使用async.js。例如:

$scope.userIds = [111,222,333,444];
var tasks = {};
$scope.userIds.each(function(id) {
    tasks[id.toString()] = function(callback) {
        $http.get("/users/"+id).success(function(data) {

            //you can update Html at here

            callback(null, data);
        });
    };
});

async.parallel(tasks, function(err, users) {
    //users: { '111': { id: ???, name: ??? }, '222': { id: ???, name: ??? },...} 
});