我正在为一个项目开发react + firestore 9,我一直在寻找一种检索数据以显示在我的应用程序上的方法。问题是,我看到很多人推荐这个语法:
import firebase, { db } from 'path/to/firebase';
import {collection, getDocs, getDoc, query, doc, addDoc, deleteDoc, updateDoc} from "firebase/firestore";
// CONSULTA
const result = await getDocs(query(collection(db, 'persons')));
我的问题是关于异步函数外部的等待,我总是得到相同的错误,我通过创建一个异步函数来包装等待,如下所示:
import firebase, { db } from 'path/to/firebase';
import {collection, getDocs, getDoc, query, doc, addDoc, deleteDoc, updateDoc} from "firebase/firestore";
// CONSULTA
const result = async() => {
const foo = await getDocs(query(collection(db, 'persons')));
};
那么,有没有什么我可以做的,让它在异步函数之外工作,或者我注定要永远在异步函数中包装等待?
发布于 2021-11-09 05:21:09
如果我没记错,等待只能在异步函数中使用。但您可以使用.then(() => {})并在其中添加逻辑,您将确保在promise之后触发代码,并定义您的数据。
对于你来说,我猜你想要这样的东西
getDocs(query(collection(db), 'persons')))
.then((foo) => {
// do something foo is defined
// code outside this scope will be triggered before the .then
})
.catch(err => console.log("there is an error", err));
请记住,异步函数总是会返回一个promise,所以即使您将代码包装在异步函数中,最后也必须使用.then()。因此,您可能希望继续使用.then,因为使用.then不需要异步函数
https://stackoverflow.com/questions/69898745
复制