Skip to content

Instantly share code, notes, and snippets.

@vladfr
Last active May 9, 2023 07:34
Show Gist options
  • Save vladfr/70677e79d93ccce8a3f3d48e8aaaeb9b to your computer and use it in GitHub Desktop.
Save vladfr/70677e79d93ccce8a3f3d48e8aaaeb9b 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 campaignsRef.doc(campaign.id).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)
}
@sunrise1234321
Copy link

if i change
let tasksRef = await campaignsRef.doc(campaign.id).collection('tasks').get();
to
let tasksRef = await campaign.collection('tasks').get();

It doesnt works. Why ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment