我正在为一个项目开发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')));
};
所以;我可以做些什么来让它在异步函数之外工作,还是我注定要永远将等待包装在异步函数中?
最佳答案
如果我没记错的话,await 只能在 async 函数中使用。但是您可以使用 .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
关于javascript - 在异步函数外部使用await,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69898745/