【问题标题】:React native firebase how to return promise listReact native firebase如何返回承诺列表
【发布时间】:2022-02-05 08:30:01
【问题描述】:

我编写了一个函数,它按照添加日期的顺序从 Firestore 数据库中获取项目。内部打印语句有效 - 它按预期打印出列表中的数据。但是,当我尝试调用该函数时,我得到了一个承诺。

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

我如何处理这个 Promise 并从中检索数据?

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

【问题讨论】:

  • 简短的回答是使用.then(result => )。但是,建议在绝望地开枪打死自己之前了解 promise 的工作原理。 nodejs.dev/learn/understanding-javascript-promises
  • @OFRBG 我应该在代码的哪一部分使用 .then()?这就是我所坚持的
  • Promise 是具有一些标准属性的对象。你的 async 函数返回一个 Promise(因为这就是 async 的工作方式),所以你需要 .then 它返回值。 fetch_recent_items().then

标签: javascript firebase react-native firebase-realtime-database


【解决方案1】:

onSnapshot() 用于将实时侦听器附加到某个数据位置。

但是,由于您尝试按需获取数据,因此您应该使用 getDocs() 来仅获取该数据一次。

请记住,Firebase SDK 是异步 API。不要陷入这样的陷阱,即仅仅因为一条线在另一条线之上,它们就会以相同的顺序执行。这些 API 必须使用 .then.catchasync/await 进行适当的链接,此外还要确保将任何 Promise 链返回给调用者。你可以阅读 Promises herehere,甚至看看 Web Dev Simplified's video series

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!

因为你在这里使用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!
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-18
    • 2018-09-27
    • 2017-01-11
    • 1970-01-01
    • 2017-03-11
    • 2018-09-16
    • 2020-11-20
    相关资源
    最近更新 更多