返回的不是空的,但说长度为0

问题描述 投票:0回答:1

我正在通过使用快照从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
typescript firebase asynchronous firebase-realtime-database
1个回答
1
投票

到您的return connections运行时,connections.push(...)调用尚未运行。因此,您总是返回一个空数组。 console.log(connectionsOfUser)可能似乎起作用,因为Chrome开发人员工具会在填充数组时更新该数组。如果要查看当前值是什么,可以使用console.log(JSON.stringify(connectionsOfUser))记录该值,这将显示空数组。

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

  1. 您的getConnections未标记为async
  2. 您没有返回一个更高版本的数组的承诺,而是一个空数组。

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

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);
© www.soinside.com 2019 - 2024. All rights reserved.