首页 > 解决方案 > 返回不为空,但表示长度为 0

问题描述

我通过使用快照从firebase返回数据并将其推送到我自己的数组。当我 console.log 它时,它确实包含元素,但是 console.log 的长度为 0。

getConnections( user ) {
    const connections = [];
    const connectionsRef = this.db.database.ref( this.dbPath + user.id + '/connections/');
    connectionsRef.on('value', snapshot => {
            snapshot.forEach( childSS => {
                connections.push( childSS.child('personID').val() );
            });
    });
    return connections;
}



const connectionsOfUser = await this.chatService.getConnections( user );
            console.log(connectionsOfUser); // Gives result
            console.log(connectionsOfUser.length); // Shows 0

标签: typescriptfirebaseasynchronousfirebase-realtime-database

解决方案


到您return connections运行时,connections.push(...)呼叫尚未运行。所以你总是返回一个空数组。这console.log(connectionsOfUser)似乎可行,因为 Chrome 开发工具会在填充数组时更新数组。如果您想查看当前的值是多少,可以使用 记录它console.log(JSON.stringify(connectionsOfUser)),这将显示空数组。

await在这里不起作用,因为:

  1. getConnections的未标记为async
  2. 你现在不是返回一个以后数组的承诺,而是一个空数组。

一个简单的解决方法是只使用 Promise:

getConnections( user ) {
    const connectionsRef = this.db.database.ref( this.dbPath + user.id + '/connections/');
    return connectionsRef.once('value', snapshot => {
        const connections = [];
        snapshot.forEach( childSS => {
            connections.push( childSS.child('personID').val() );
        });
        return connections;
    });
}

this.chatService.getConnections( user ).then((connections) => {
    console.log(connectionsOfUser); // Gives result
    console.log(connectionsOfUser.length); // Shows 0
})

所以在这里:

  • 我们使用once而不是on,因为on()可能会触发多次,并且我们只能返回一次结果。
  • 我们从回调内部返回连接,然后在函数的顶层使用另一个返回将它们冒泡。
  • 然后我们then()在调用代码中使用来获取连接。

您现在可能可以将其标记getConnections为异步,然后await像您尝试的那样调用它:

const connectionsOfUser = await this.chatService.getConnections( user );
console.log(connectionsOfUser.length);

推荐阅读