Last active
May 9, 2023 07:34
-
-
Save vladfr/70677e79d93ccce8a3f3d48e8aaaeb9b to your computer and use it in GitHub Desktop.
Use async/await and for..of in Cloud Firestore
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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) | |
} |
Thank you this thread Vlad!
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
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
".