【发布时间】: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