Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

153
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda