Skip to content

Instantly share code, notes, and snippets.

@vladfr
Last active May 9, 2023 07:34
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • 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)
}
@AurelienLoyer
Copy link

AurelienLoyer commented Jun 28, 2019

let is missing in you for of syntax

for (let campaign of activeRef.docs) {
    for(let task of tasksRef.docs) {
    } 
}

@arausmatias
Copy link

arausmatias commented Jun 14, 2020

ooh yess 👏🏻👏🏻 !! thanks Bro!! I was days without being able to solve this, locked with the forEach.
I had to make a slight modification, as I was getting the following error "Unexpected await inside a loop. no-await-in-loop".

/* eslint-disable no-await-in-loop */ 
for (let 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())
    } 
}
/* eslint-enable no-await-in-loop */

@rohit1101
Copy link

Thank you this thread Vlad!

@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