如何赚$q.在这种情况下都有效

How to make $q.all work in this case?

本文关键字:这种情况下 有效 何赚      更新时间:2023-09-26

我正在尝试使用$q。所有这些都在下面的代码中。但我想我误解了一些关键的想法,因为它没有像我预期的那样工作。如果有人能给我一些建议,我将非常感激。

问题在$q.all(toSend.pie.slices).then():

var someData = {...};
var toSend = {
    pie: {
        slices: []
    }
};
toSend.pie.slices = generatePieSlice(someData);

$q.all(toSend.pie.slices).then(function(data){
    if(data) {      
        console.log(data);  // this is undefined :(        
        //do something else
    }
});  

function generatePieSlice(data) {
    var arr = [];
    if(data) {
        angular.forEach(data, function(resp_o, resp_n){
            arr.push({
                name: resp_o.display,
                marketValue: resp_o.value,
                percentage: resp_o.percentage,
                key: resp_n
            });
        });
    }
    $q.all(arr).then(function(data) {
        if(data) {
            console.log(data); // this gives me with the correct data
            return data;
        }
    });
}

感谢所有评论者的帮助。这是我对其他感兴趣的人的最终解决方案:)

var someData = {...};
var toSend = {
    pie: {
        slices: []
    }
};

$q.all({
    pieSlices: generatePieSlice(someData)
}).then(function(data){
    if(data) {      
        toSend = {
            pie: {
                slices: data.pieSlices
            }
        };
        // deferred.resolve(toSend) or something else :)
    }
});  

function generatePieSlice(response) {
    var arr = [];
    if(response) {
        angular.forEach(data, function(resp_o, resp_n){
            arr.push({
                name: resp_o.display,
                marketValue: resp_o.value,
                percentage: resp_o.percentage,
                key: resp_n
            });
        });
    }                
    return arr;
}