Skip to content

Instantly share code, notes, and snippets.

@sunrise1234321
Forked from vladfr/1-standard.js
Last active December 4, 2021 13:43
Show Gist options
  • Save sunrise1234321/295da18f7a5af5ee3597f3c9c8f002e6 to your computer and use it in GitHub Desktop.
Save sunrise1234321/295da18f7a5af5ee3597f3c9c8f002e6 to your computer and use it in GitHub Desktop.
Use async/await and for..of in Cloud Firestore
// In a Firestore standard example, we quickly create a 'xmas tree' of nested stuff
// We use Promises directly: get().then(callback) and use snapshot.forEach() to iterate
let campaignsRef = db.collection('campaigns');
let activeCampaigns = campaignsRef.where('active', '==', true).select().get()
.then(snapshot => {
snapshot.forEach(campaign => {
console.log(campaign.id);
let allTasks = campaignsRef.doc(campaign.id).collection('tasks').get().then(
snapshot => {
snapshot.forEach(task => {
console.log(task.id, task.data())
});
}
)
});
})
.catch(err => {
console.log('Error getting documents', err);
});
// In the async/await example, we need to wrap our code inside a function
// and mark it as 'async'. This allows us to 'await' on a Promise.
async function process_tasks() {
let campaignsRef = db.collection('campaigns')
let activeRef = await campaignsRef.where('active', '==', true).select().get();
for (campaign of activeRef.docs) {
console.log(campaign.id);
let tasksRef = await campaign.collection('tasks').get();
for(task of tasksRef.docs) {
console.log(task.id, task.data())
}
}
}
// Call our async function in a try block to catch connection errors.
try {
process_tasks();
}
catch(err) {
console.log('Error getting documents', err)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment