简体   繁体   English

角度服务预计$ q.promise

[英]Angular service foreach $q.promise

i have the following function: 我有以下功能:

    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
}

Problem is that the d.resolve(benchmarkData) is runned before actual data has been put into it. 问题是d.resolve(benchmarkData)在实际数据放入之前运行。

I know that this is a problem with the async $http task. 我知道这是async $http任务的一个问题。 However i am not sure how to fix it. 但是我不知道如何解决它。 Can anyone point me in the right direction? 谁能指出我正确的方向?

You are not resolving promise correctly, You should collect all the promise in array and then use $q.all to resolve the deferred promise 您没有正确解决承诺,您应该收集数组中的所有承诺,然后使用$q.all来解决延迟承诺

Code

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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