In the process of developing a web application tailored for crafting retail signage, I have integrated Firestore to manage pertinent information about these signs. One specific functionality I am working on is enabling users to effortlessly remove all existing signs with just one click labeled 'Remove all Signs.' Upon clicking this button, a dialog will pop up prompting the user to confirm the action of deleting all signs stored in the database. Once the confirmation is granted, the system should proceed to eradicate all signs from Firestore.
Essentially, each sign's unique document ID is contained within an array dubbed signIds
. The main objective here is to efficiently iterate through this array and delete each corresponding document from the collection named signs
in Firestore. Subsequently, once all deletion operations are successfully completed, I aim to return a Promise and resolve it within the event handler located in mounted()
.
My attempts at placing the Promise at various points within the code have proven futile thus far. Moreover, experimenting with incorporating async
and await
functionalities did not yield the desired outcome either.
data() {
return {
signIds: [],
}
},
methods: {
showModal(message, type) {
this.$root.$emit('openModal', {
closed: false,
text: message,
type: type
})
},
emptyQueue() {
let self = this;
let deleted = 0;
for (let id of self.signIds) {
database.collection("signs").doc(id).delete()
.then(() => {
console.log("Document successfully deleted!");
deleted++;
}).catch((error) => {
console.error("Error removing document: ", error);
});
}
// Once all signs are deleted, return new Promise
return new Promise((resolve, reject) => {
return (deleted === self.signIds.length) ? resolve() : reject(new Error('An error occurred while deleting signs.'));
});
}
},
created() {
// Retrieve and store the document id for each sign
database.collection("signs").get()
.then(snapshot => {
snapshot.forEach(doc => {
this.signIds.push(doc.id);
})
});
},
mounted() {
// Trigger the deletion of all signs from the database when the user confirms.
this.emptyQueue()
.then(() => {
setTimeout(function() {
self.showModal('All signs were successfully removed.', 'success');
}, 300);
}).catch(() => {
setTimeout(function() {
self.showModal('An error has occurred. Some signs were not removed.', 'error');
}, 300);
})
}
The anticipated behavior is for the new Promise to only be returned after resolving Firebase's Promises; however, the current issue lies in the fact that the new Promise gets returned immediately upon completion of the for
loop.