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

165
Vistas
break from a for loop on the result of an async function

I am working on a code where I have to query a firestore collection and get one random document, but if the id of the document is the same as the one I have in my primaryTag, then I need to query the collection again. I am using a small for loop of 5 iterations to test.

let myPrimaryTag = 'abcd1234';
   
 for(let i = 0 ; i < 5 ; i++){
 
/* randomTag is an async function which returns a random document from firestore   collection */

     randomTag()
     .then(resultId => {
         
         if(myPrimaryTag == resultId){

            console.log('result is same as primarytag ',result);
            // If resultId is same, need to continue in the loop

         } else {

            console.log('different result encountered ',result);
            // If resultId is not same, then need to break here

          }  
      });
   }

I need to know how I can exit from the loop with the result once I get a different resultId? I am new to both firebase and stackoverflow.

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

0

The easiest way to do it is to make a loop that will end only when the correct document is found. It's simple, but it's wrong.

const myPrimaryTag = 'abcd1234';

function getNewDocument(primaryTag) {   
  while(true) {
/* randomTag is an async function which returns a random document 
   from firestore   collection */
  randomTag()
    .then(resultId => {
      if(primaryTag !== resultId) {
        return resultId;
      }
    }
  }
}

console.log(getNewDocument(myPrimaryTag));

There are some issues:

  • if there's only one document in the database with primary tag, then this loop will never end
  • we need to use async/await or all the calls into firebase will be done at the same time
const myPrimaryTag = 'abcd1234';

/* 
   Function will exit if we found the new random document with Id different 
   from the primary tag or if we didn't find such document after 3 attempts
*/
async function getNewDocument(primaryTag) {
  const maxAttempts = 3;
  for(let attempt = 0; attempt < maxAttempts; attempt++) {
/* randomTag is an async function which returns a random document 
   from firestore collection */
  const resultId = await randomTag();
  if(primaryTag !== resultId) {
    return resultId;
  }
}

const newDocument = await getNewDocument(myPrimaryTag);
console.log(newDocument);
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