简体   繁体   English

Firestore 返回一个空数组

[英]Firestore returning an empty array

I have this function here in a separate file, where:我在一个单独的文件中有这个 function,其中:

export const getListOfChannels = (id) => {
  const channels = []

  firestore.collection("channels").where("channelId", "==", id).get().then(querySnapshot => {
    querySnapshot.forEach(doc => {
      channels.push(doc.data().id)
    })
  })
  return channels
}

And in another file, I'm doing:在另一个文件中,我正在做:

// This is returning an empty array
const returnFromFirebase = getListOfChannelsIdWithCommunityId(id)

It wasn't supposed to return an empty array, because if I do a console.log(doc.data().id) I can see the data.它不应该返回一个空数组,因为如果我执行console.log(doc.data().id)我可以看到数据。

Am I doing something wrong?难道我做错了什么?

Firebase APIs (and any API that returns a promise) are asynchronous and return immediately, before the query is complete. Firebase API(以及任何返回承诺的 API)是异步的,并在查询完成之前立即返回。 The callback you provide via then is invoked some time later, after the results are available.在结果可用之后,您通过then提供的回调会在一段时间后被调用。 There is no guarantee how quickly this will happen.无法保证这会以多快的速度发生。 As such, it's not possible to make a function that returns the query results immediately.因此,不可能制作一个立即返回查询结果的 function。

For asynchronous calls, what you're supposed to do is make your wrapper function also return a promise, and make the caller use that promise to get the results:对于异步调用,你应该做的是让你的包装器 function 也返回一个 promise,并让调用者使用 promise 来获得结果:

export const getListOfChannels = (id) => {
  return firestore.collection("channels").where("channelId", "==", id).get();
}

getListOfChannelsIdWithCommunityId(id).then(querySnapshot => {
  querySnapshot.forEach(doc => {
    channels.push(doc.data().id)
  })
})

There are a lot of variations on how to do this, but there is no alternative to dealing with that promise asynchronously.如何做到这一点有很多变体,但除了异步处理 promise 之外,别无选择。 I strongly suggest learning how promises work, as it is critical to writing effective JavaScript.我强烈建议学习 Promise 的工作原理,因为它对于编写有效的 JavaScript 至关重要。

getListOfChannels is having code that does async call and you are returning channels outside of then and therefore it will always be empty. getListOfChannels具有执行异步调用的代码,并且您在此之外then channels ,因此它将始终为空。

So, return the promise所以,返回 promise

export const getListOfChannels = (id) => {
  const channels = []

  return firestore.collection("channels").where("channelId", "==", id).get().then(querySnapshot => {
    querySnapshot.forEach(doc => {
      channels.push(doc.data().id)
    })
    return channels;
  })
}

And in Another file access it in then block然后在另一个文件中访问它then阻止

let returnFromFirebase = [];
getListOfChannelsIdWithCommunityId(id).then((res) => {
  returnFromFirebase = res;
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM