I'm trying to write some asynchronous code in JavaScript, especially I want the code to be executed after a certain functions has finished the execution.
Below is my code:
function triggerFunction(duration) {
var db = firebase.firestore();
db.collection('users').get().then((querySnapshot) => {
querySnapshot.forEach((doc) => {
var data=doc.data();
db.collection('users').doc(doc.id).collection('#aName').get().then((querySnapshot1) => {
querySnapshot1.forEach((doc1) => {
var firstData = doc1.data()
var newID = createRandomId()
var alreadyExist = checkAlreadyElementDB(firstData.appType, doc.id)
if(firstData.open == true && !alreadyExist){
console.log("Entered here: " + alreadyExist)
db.collection('#name').doc(newID).set({
#NotImportant
})
db.collection('users').doc(doc.id).collection('#aName').doc(doc1.id).update({
open: false
})
} else if(firstData.open == true && alreadyExist){
db.collection('users').doc(doc.id).collection('#aName').doc(doc1.id).update({
open: false
})
}
})
})
});
});
setTimeout(triggerFunction, duration);
}
What I want is first to receive the result from the function
var alreadyExist = checkAlreadyElementDB(firstData.appType, doc.id)
Then to continue to check the following part of the code
if(firstData.open == true && !alreadyExist){
console.log("Entered here: " + alreadyExist)
db.collection('#name').doc(newID).set({
#NotImportant
})
db.collection('users').doc(doc.id).collection('#aName').doc(doc1.id).update({
open: false
})
} else if(firstData.open == true && alreadyExist){
db.collection('users').doc(doc.id).collection('#aName').doc(doc1.id).update({
open: false
})
}
I will really appreciate your help with this problem!
checkAlreadyElementDB() function looks like this:
function checkAlreadyElementDB(appType, userID){
var db = firebase.firestore();
db.collection('#name').get().then((querySnap) => {
querySnap.forEach((doc) => {
var opFCData = doc.data();
if(opFCData.appType == appType && opFCData.userID == userID){
// console.log("I HAVE ENTERED HERE")
return true
}
});
});
return false
}
db.collection('#name').get()is asynchronous, you need to return a Promise from checkAlreadyElementDB, and where you use checkAlreadyElementDB you need to use .then (or aysnc/await) to wait for that promise to resolvedb.collection('#name').get()returns a Promise ... as you can see by the.then( .... )... anywhere you've used.thenin your code, you're using promises