数组仅在第0个索引中添加

时间:2017-02-22 16:53:38

标签: javascript angular typescript

我正在编写一个函数,我需要将元素添加到数组中。我从我的数据库中获取数据。当将元素添加到其中时,所有元素都只被添加到数组[0]中rowData。

private createRowData() {
        var rowData:any[] = [];
        this.wakanda.catalog.then(ds => {
            ds.Group.query({select : 'groupName'}).then(op => {
                for(let entity of op['entities']){
                    rowData.push(
                    {row : entity.groupName});
                }
            });
        });
        return rowData;
    }

我的输出就像这样

enter image description here

我需要这样的东西

enter image description here

我该如何解决?

提前致谢

1 个答案:

答案 0 :(得分:1)

  

在上面的函数中,您正在使用异步的DB调用,然后您在不等待结果的情况下发送响应。

因此,在这种情况下,您将获得rowData.length 0。

在回调响应后发送结果。

试试这个:

    private createRowData() {
        return new Promise((resolve, reject) => {
            var rowData: any[] = [];
            this.wakanda.catalog.then(ds => {
                ds.Group.query({ select: 'groupName' }).then(op => {
                    for (let entity of op['entities']) {
                        rowData.push({ row: entity.groupName });
                    }
                    resolve(rowData); // Send result from here
                });
            }).catch(reject);
        })
    }