-
-
Save sunrise1234321/295da18f7a5af5ee3597f3c9c8f002e6 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 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