简体   繁体   English

React Native firebase 如何返回 promise 列表

[英]React native firebase how to return promise list

I have written a function that fetches items from a firestore database in order of date added.我写了一个 function,它按照添加日期的顺序从 firestore 数据库中获取项目。 The inner print statement works - it prints out the data in a list as expected.内部打印语句有效 - 它按预期打印出列表中的数据。 However, when I try to call the function I get a promise.但是,当我尝试调用 function 时,我得到了 promise。

async function fetch_recent_items(){
    const db = getFirestore(app);
    const col = collection(db, "my col")
    const q = query(col, orderBy("date", "asc"))

    const result = onSnapshot(q, (snapshot) => {
        items = [];
        snapshot.docs.forEach((doc) => {
            items.push(doc.data())
        })

        return items
    })
    console.log(items) // Prints list (desired result)
    return result 
    
}
console.log(fetch_recent_items()) // Prints promise

How do I process this promise and retrieve data from it?如何处理这个 promise 并从中检索数据?

Promise {
  "_U": 0,
  "_V": 0,
  "_W": null,
  "_X": null,
}
  • "firebase": "^9.6.3" “火力基地”:“^9.6.3”
  • "react-native-web": "0.17.1" “反应原生网络”:“0.17.1”
  • "react": "17.0.1" “反应”:“17.0.1”

onSnapshot() is used to attach a real-time listener to certain data location. onSnapshot()用于将实时侦听器附加到某个数据位置。

However, because you are trying to fetch data on-demand, you should be using getDocs() instead to get that data just once.但是,因为您正在尝试按需获取数据,所以您应该使用getDocs()来仅获取该数据一次。

Remember that the Firebase SDKs are asynchronous APIs.请记住,Firebase SDK 是异步 API。 Don't fall into the trap of thinking that just because one line is above another that they will execute in the same order.不要陷入这样的陷阱,即仅仅因为一条线在另一条线之上,它们就会以相同的顺序执行。 These APIs must be appropriately chained using .then , .catch and async / await , in addition to making sure you return any Promise chains to the caller.除了确保将任何 Promise 链返回给调用者之外,这些 API 必须使用.then.catchasync / await进行适当的链接。 You can read up on Promises here and here , or even have a look at Web Dev Simplified's video series .您可以在此处此处阅读 Promises,甚至可以查看Web Dev Simplified 的视频系列

async function fetch_recent_items(){
    const db = getFirestore(app)
    const col = collection(db, "my col")
    const q = query(col, orderBy("date", "asc"))

    return getDocs(q)
        .then(querySnapshot => {
            return querySnapshot.docs // gets array of QueryDocumentSnapshot objects
                .map(doc => doc.data()) // consider using ({ id: doc.id, ...doc.data() }) instead
        })
}

fetch_recent_items()
    .then((items) => console.log(items))
    .catch((error) => console.error(error)) // don't forget error handling!

Because you are using async here, you can slightly simplify this to:因为你在这里使用async ,你可以稍微简化为:

async function fetch_recent_items(){
    const db = getFirestore(app)
    const col = collection(db, "my col")
    const q = query(col, orderBy("date", "asc"))

    const querySnapshot = await getDocs(q);

    return querySnapshot.docs // gets array of QueryDocumentSnapshot objects
        .map(doc => doc.data()) // consider using ({ id: doc.id, ...doc.data() }) instead
}

// IF this is also in an async function, but don't make components async! - use useEffect/useAsyncEffect for that
try {
    const items = await fetch_recent_items();
    console.log(items)
} catch (error) {
    console.error(error) // don't forget error handling!
}

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

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