简体   繁体   中英

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.

I know that this is a problem with the async $http task. 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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