如何从 Promise 结果中获取数组?
我目前正在尝试从 firestore 数据库获取数据。我可以得到一个数组的 Promise,但我只想得到数组。我的代码如下所示:
function getUserData(){
return database.users.where("uid", "==", currentUser.uid).get().then((q) => {
return q.docs.map(doc => doc.data())
})
}
var data = getUserData()
console.log(data)
I'm currently trying to get data from a firestore database. I can get a promise with an array, but I want to get just the array. My code looks like this:
function getUserData(){
return database.users.where("uid", "==", currentUser.uid).get().then((q) => {
return q.docs.map(doc => doc.data())
})
}
var data = getUserData()
console.log(data)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你缺少异步/等待。
您还需要等待函数调用。
阅读异步代码并使用 async/await。您将返回 Promise,因为当您尝试控制台输出时,代码尚未完成处理,因此它处于 pending promise state,而不是已解决或拒绝。
编辑: .then 是正确的,但它只是告诉它在函数调用中做什么。所以你也必须等待函数调用。
You're missing async/await.
You also need to await the function call.
Read up on asyncronous code and using async/await. You're getting "promise" returned because when you're trying to console the output, the code hasn't finished processing yet, so it's in a "pending promise state" instead of resolved or rejected.
Edit: The .then is correct, but it's only telling it what to do in the function call. So you have to await the function call as well.
您试图从返回 Promise 的函数中获取结果,而不是数组本身,因此您需要等待 Promise 完成执行并返回结果。您可以通过两种方式执行此操作:
使用
then
:使用
async
/await
:You're trying to get a result from a function that returns the promise, not the array itself, so you need to wait for the promise to finish executing and return the result. You can do it in two ways:
then
:async
/await
:您可以使用状态获取数据。
像这样。
You can get data using state.
Like this.