Shubham
Shubham

Reputation: 40

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.

Upvotes: 0

Views: 568

Answers (1)

Alexey Zelenin
Alexey Zelenin

Reputation: 730

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);

Upvotes: 0

Related Questions