Using the documentSnapshot
function in Firestore to verify the existence of a document.
The function is executed in a loop up to a value of 5.
However, even though the function runs 5 times, the value of 'i' always reflects the last value. The value is continuously printed outside the function.
user="manjoola";
private saveToken(user, token): void {
var i:number=0;
var user_document:string=user;
for(i=0;i<5;i++)
{
user_document=user+i;
console.log(user_document);
this.firestore.doc(`pushnotifications/${user_document}`).ref.get().then((documentSnapshot) => {
console.log(documentSnapshot.exists);
if(documentSnapshot.exists)
{
console.log('It exists'+user+i);
snapshot=true;
}
else
{
this.firestore.collection(`pushnotifications`).doc(`${user_document}`).set({'authtoken': user, 'fcmtoken': token});
console.log('Does not exists'+user+i);
snapshot=false;
}
snapshot=false;
}).catch(function (error)
{
console.log("Error getting document:", error);
}
);
console.log(i);
}
}
Console log:
manjoola0
messaging.service.ts:137 0
messaging.service.ts:112 manjoola1
messaging.service.ts:137 1
messaging.service.ts:112 manjoola2
messaging.service.ts:137 2
messaging.service.ts:112 manjoola3
messaging.service.ts:137 3
messaging.service.ts:112 manjoola4
messaging.service.ts:137 4
messaging.service.ts:115 false
messaging.service.ts:126 Does not existsmanjoola5
messaging.service.ts:115 false
messaging.service.ts:126 Does not existsmanjoola5
messaging.service.ts:115 false
messaging.service.ts:126 Does not existsmanjoola5
messaging.service.ts:115 false
messaging.service.ts:126 Does not existsmanjoola5
messaging.service.ts:115 true
messaging.service.ts:119 It existsmanjoola5