我有以下功能:

    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任务的问题。但是我不确定如何解决它。谁能指出我正确的方向?

最佳答案

您没有正确解析承诺,应该将所有承诺收集到数组中,然后使用$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

关于javascript - Angular服务foreach $ q.promise,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29698440/

10-09 14:24