Sorry for the rookie question, but I am about to toss my laptop.
I'm new to js and have been struggling to understand how to use promises.
When a conversation is deleted this function is triggered and should loop throw all the messages contained in the conversation and delete them.
My problem is I don't no where to delete the messages or how to do it. How do I delete the messages?
exports.deleteMessages = functions.firestore
.document('users/{userId}/conversations/{conversationId}')
.onDelete(event => {
// Get an object representing the document prior to deletion
const deletedConversation = event.data.previous.data();
return database.collection('messages')
.where('conversationId', '==', deletedConversation.id).get()
.then(snapshot => {
snapshot.forEach(document => {
const data = document.data();
database.collection('messages').document(data.id).delete();
});
return console.log("Don't even no why I'm returning this")
})
.catch(error => {
console.log('Error when getting document ' + error)
});
});
You have to use Promise.all(), which "returns a single Promise that resolves when all of the promises in the iterable argument have resolved or when the iterable argument contains no promises."
You should do along these lines:
const promises = [];
return database.collection('messages')
.where('conversationId', '==', deletedConversation.id).get()
.then(snapshot => {
snapshot.forEach(document => {
//Create a Promise that deletes this document
//Push the Promise in the "promises" array
promises.push(deleteDocPromise(document))
});
//and return:
return Promise.all(promises);
})
.then(
//Do whatever you want in case of succesfull deletion of all the doc
)
.catch(error => {
....
});
In order to create the Promise for deletion do something like
function deleteDocPromise(document) {
//using the code of your question here
const data = document.data();
return database.collection('messages').doc(data.id).delete();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.