角度服务预计$ q.promise

时间:2015-04-17 11:53:22

标签: javascript angularjs asynchronous promise angular-promise

我有以下功能:

    this.getBenchmarkData = function () {
    var benchmarkData = [];
    var d = $q.defer();
    users.forEach(function(user){
        var dataArray = [];
        modules.forEach(function (module) {
            $http.get(api.getUrl('teamUserBenchmark', [user.user_id, module.id, user.team_id]))
                .success(function (response) {
                    response.forEach(function(result){
                        dataArray.push(result.score);
                    })
                });
        });

        benchmarkData.push(dataArray);

    });
    d.resolve(benchmarkData);

    return d.promise
}

问题是在将实际数据放入其中之前运行d.resolve(benchmarkData)

我知道这是异步$http任务的问题。但是我不知道如何解决它。有人能指出我正确的方向吗?

1 个答案:

答案 0 :(得分:3)

您没有正确解决承诺,您应该收集数组中的所有承诺,然后使用$q.all来解决延期承诺

<强>代码

this.getBenchmarkData = function () {
var benchmarkData = [];
var d = $q.defer(), promise = [];
users.forEach(function(user){
    var dataArray = [];
    modules.forEach(function (module) {
        var currentPromise = $http.get(api.getUrl('teamUserBenchmark', [user.user_id, module.id, user.team_id]))
            .success(function (response) {
                response.forEach(function(result){
                    dataArray.push(result.score);
                })
            });
        promise.push(currentPromise); //<--creating promise array here
    });
});
$q.all(promise).then(function(){ 
   benchmarkData.push(dataArray); //added whole data.
   d.resolve(benchmarkData); //resolved after all promise gets completed
});


return d.promise