typescript - 返回不为空,但表示长度为 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
解决方案
到您return connections
运行时,connections.push(...)
呼叫尚未运行。所以你总是返回一个空数组。这console.log(connectionsOfUser)
似乎可行,因为 Chrome 开发工具会在填充数组时更新数组。如果您想查看当前的值是多少,可以使用 记录它console.log(JSON.stringify(connectionsOfUser))
,这将显示空数组。
你await
在这里不起作用,因为:
- 您
getConnections
的未标记为async
- 你现在不是返回一个以后数组的承诺,而是一个空数组。
一个简单的解决方法是只使用 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);
推荐阅读
- google-cloud-platform - 如何直接从谷歌驱动器上传到谷歌云存储桶?使用我的 python 脚本文件
- django - 找不到页面 (404) 没有跟踪匹配给定的查询。错误 Django
- pine-script - 来自非 ATR 触发入场点的 ATR 追踪止损
- python - 从 .txt 文件中提取数据,使用的变量存在问题
- mongodb - Mongodb 性能 - 批量更新与串行更新与串行获取和更新
- django - TypeError:调用“create()”时出现“TypeError”。您可能需要将该字段设置为只读,或覆盖 create() 方法来处理此问题
- python - get() 返回多个——Django Restframework
- node.js - 使用 nodejs 和 lambda 的无服务器 - 函数不在 lambda 上调用,但在本地调用
- html - 使用动态输入字段/larave 和 jQuery 将多行保存到数据库中
- jquery - Django 数据表视图过滤器/搜索