Home > Net >  await used outside an async function
await used outside an async function

Time:11-10

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')));
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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')));
};
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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?

CodePudding user response:

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

  • Related