简体   繁体   English

从 Firebase 查询返回结果数组

[英]Returning array of results from Firebase query

I'm using the @react-native-firebase wrapper to interact with Firebase's Firestore.我正在使用@react-native-firebase包装器与 Firebase 的 Firestore 进行交互。 I have a function which performs some querying to one of my collections and the intended response should be an Array object containing each found document.我有一个 function 对我的 collections 之一执行一些查询,预期的响应应该是一个包含每个找到的文档的数组 object。

My function currently looks like:我的 function 目前看起来像:

export const backendCall = async => {
  let response = [] 
  firestore()
  .collection('collection')
  .where('id', '==', 1)
  .onSnapshot(documentSnapshot => {
    documentSnapshot.forEach(x => response.push(x.data())) 
  })
  return response 

On my UI, I use a react-native Button component which calls this function onPress :在我的 UI 上,我使用了一个react-native Button组件,它调用了这个 function onPress

<Button 
  title="get" 
  onPress={() => {
    backendCall().then(response => console.log(response)) 
  }}
/> 

Using console.log I am able to observe the expected Array object (but with a "value below was evaluated just now" icon. If however, I change the onPress to console.log(JSON.stringify(response)) , the Array object is empty.使用console.log我能够观察到预期的Array object (但带有“刚刚评估了下面的值”图标。但是,如果我将onPress更改为console.log(JSON.stringify(response)) ,则Array object是空的。

I'm assuming this has something to do with the async calls but I can't quite figure out how to fix it.我假设这与异步调用有关,但我不太清楚如何解决它。 Would appreciate some pointers.将不胜感激一些指针。

You're returning the response without waiting for the result from your firebase query.您无需等待 firebase 查询的结果即可返回响应。 To wait for the response to arrive before returning, you can use Promise.要在返回之前等待响应到达,您可以使用 Promise。

export const backendCall = () => {
    return new Promise(resolve => {
        firestore()
            .collection('collection')
            .where('id', '==', 1)
            .onSnapshot(documentSnapshot => {
                const response = []
                documentSnapshot.forEach(x => response.push(x.data()))
                resolve(response)
            })
    })
}

You can use Array.map to make the for loop looks nicer.您可以使用 Array.map 使 for 循环看起来更好。

const response = documentSnapshot.map(x => x.data())
resolve(response)

You can also read docs from a QuerySnapshot :您还可以从QuerySnapshot读取docs

export const backendCall = async () => {
  const qs = firestore().collection('collection').where('id', '==', 1).get()
  return qs.docs.map(x => x.data())
}

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

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