Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

161
Vistas
await used outside an async function

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?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda