使用Ext.Function.defer(setTimeout)时为什么无法访问数组的值?

时间:2017-11-05 16:12:19

标签: javascript extjs

我基本上是使用Ext.Function.defer向数组添加元素,并且元素被添加到数组中,但是当我控制出数组时它会输出空数组。这是我的代码:

   var arr = [];
    Ext.Function.defer(function () {
        Ext.Array.forEach(me.query('grid'), function (grid) {
            arr.push(grid.collapseTool.getId()); // [1 ,4 , 6 , 8 ,10]
        });
    }, 1000);
    console.log(arr); // outputs empty array []

谁能告诉我我缺少什么?提前谢谢!

1 个答案:

答案 0 :(得分:3)

这是因为defer将以异步方式运行,您正在访问arr状态,其中未填充您想要的数据

编辑:您可以测试此代码以了解延迟

Ext.Function.defer(function() {
    console.log("You will see this message later although it is written first");
}, 1000);
console.log("You will see this message first although it is written after");

编辑2:示例代码

Ext.Function.defer(function() {
    var arr = [];
    Ext.Array.forEach(panel.query('grid'), function(grid) {
        arr.push(grid.collapseTool.getId());
    });
    onDone(arr);
}, 1000);

function onDone(arr) {
    console.log(arr);
}