Estoy trabajando en un código donde tengo que consultar una colección de firestore y obtener un documento aleatorio, pero si la identificación del documento es la misma que tengo en mi etiqueta principal, entonces necesito consultar la colección nuevamente. Estoy usando un pequeño bucle for de 5 iteraciones para probar.
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 } }); }Necesito saber cómo puedo salir del ciclo con el resultado una vez que obtenga un ID de resultado diferente. Soy nuevo tanto en firebase como en stackoverflow.
La forma más fácil de hacerlo es hacer un bucle que terminará solo cuando se encuentre el documento correcto. Es simple, pero está mal.
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));Hay algunos problemas:
primary tag , este ciclo nunca terminaráfirebase se realizarán al mismo tiempo 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);