Reputation: 40
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
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:
primary tag
, then this loop will never endfirebase
will be done at the same timeconst 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