I'm working on react + firestore 9 for a project and i've been looking at a way of retrieving data to display on my application. Thing is I see a lot of people recommending this syntax:
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')));
My question is about the await outside an async function, I allways get the same error that I solve by creating an async function to wrap the await like so:
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'))); };
So; is there something I can do to make it work outside the async function, or am I doomed for eternity to wrap awaits in async functions?
If I'm not wrong await can be only used in async function. But you can use .then(() => {}) and add logic in it, you will be sure that the code will be triggered after the promise and your data will be defined.
In your case I guess you want something like this
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));
Remember that async function will always return a promise and so even you you wrap your code inside async function you will have to use a .then() at the end. So maybe you want to stay with .then instead because you don't need async function to use .then
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.