如何加载用户列表并并行呈现它们

How to load a list of users and render them in parallel?

本文关键字:并行 列表 用户 何加载 加载      更新时间:2023-09-26

在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 中还有更好的方法吗?

你可以通过使用一系列承诺来做到这一点:

    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
    });
我不知道

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: ??? },...} 
});