全局变量的值仍未显示未定义的'尽管在功能中显示正确的价值

时间:2016-07-25 21:15:18

标签: javascript angularjs ajax global-variables

我在所有函数之外定义了一个全局数组,如下所示:

var invoice2016Header = new Array(12);

然后我在loadArray()函数中填充它:

function loadArray() {

    var promiseArray = [];

for (i = 0; i < 12; i++) {

        promiseArray.push(
            new Promise(function (resolve, reject) {
                runOWSLS("Invoice", beginning2016Months[i], closing2016Months[i], "no", function (callbackResp) {
                    invoice2016Header[i] = callbackResp.header.ynofreight;
                    alert(invoice2016Header[i]); //This returns the CORRECT value
                    resolve();
                });
            })
        );

    }


    Promise.all(promiseArray).then(function () {

            for (i = 0; i < 12; i++){

                alert(invoice2016Header[i]); //This returns UNDEFINED for every value??
            }


        });
}

由于 invoice2016Header [] 数组位于全局范围内,因此我无法理解为什么当Prom声称它被引用时,我得到了UNDEFINED。它不应该具有之前分配给它的价值吗?

JS做范围的方式有时会让我失望......

- 编辑 -

以下是控制台日志的最后一位:

monthlyCharting.js:148 OWSLS Ran Successfully
monthlyCharting.js:149 Object {data: Object, status: 200, config: Object, statusText: "OK"}
monthlyCharting.js:437 422351.60
monthlyCharting.js:148 OWSLS Ran Successfully
monthlyCharting.js:149 Object {data: Object, status: 200, config: Object, statusText: "OK"}
monthlyCharting.js:437 242180.36
monthlyCharting.js:452 12 - undefined

1 个答案:

答案 0 :(得分:0)

我改变了对下面代码调用promise的方式,现在它可以工作:

function loadArray() {


    ...


var promiseArray = [];


var get2016Totals = function (i) {
        return new Promise(function (resolve) {
            runOWSLS("Invoice", beginning2016Months[i], closing2016Months[i], "no", function (callbackResp) {
                $scope.invoice2016Header[i] = callbackResp.header.ynofreight;
                console.log($scope.invoice2016Header[i]);
                resolve();
        });
    })
}

for (var i = 0; i < 12; i++) {

    promiseArray.push(get2016Totals(i));

}


Promise.all(promiseArray).then(function () {

        for (var month = 0; month < 12; month++){

            console.log($scope.invoice2016Header[month]);
        }

        google.charts.load('current', {packages: ['corechart', 'bar']});
        google.charts.setOnLoadCallback(drawChart);
    });
}