Asynchronous Firebase Query To Response
I'm trying to get all documents from a firebase collection, create a list and return it on request with a Cloud Function, but I'm struggling with the asynchronous nature of JavaScr
Solution 1:
I cleaned the code up a bit and replaced your Promise based code with async await
. You can try running this:
async await version
firebase.initializeApp(firebaseConfig);
const db = firebase.firestore();
const buildItems = async () => {
return db.collection('reminders').get();
};
exports.view = functions.https.onRequest(async (req, res) => {
try {
const reminders = await buildItems();
let items = '';
reminders.forEach(qs => {
items.concat(`<li> ${qs.data().name} </li>`);
});
return res
.status(200)
.send(`
<!doctype html>
<head>
<title>Reminders</title>
</head>
<body>
<ul>
${items}
</ul>
</body>
</html>
`);
} catch (error) {
/** Handle error here */
}
});
Promise based version
firebase.initializeApp(firebaseConfig);
const db = firebase.firestore();
const buildItems = () => {
return db.collection('reminders').get();
};
exports.view = functions.https.onRequest((req, res) => {
buildItems()
.then(reminders => {
let items = '';
reminders.forEach(qs => {
items.concat(`<li> ${qs.data().name} </li>`);
});
return res
.status(200)
.send(`
<!doctype html>
<head>
<title>Reminders</title>
</head>
<body>
<ul>
${items}
</ul>
</body>
</html>
`);
})
.catch(error => {
/** Handle Error here */
});
});
If you are having still having trouble, you should try if the collection reminders
actually contains the documents you want to fetch.
The .size
property is available in [QuerySnapShots][1]
in Firebase query snapshot results. If the snapshot size is 0.
Post a Comment for "Asynchronous Firebase Query To Response"