I'm trying to get data from my Firestore database. Based on Firestore documentation I wrote this:
const productsRef = db.collection('products');
const snapshot = await productsRef.get();
snapshot.forEach(doc => {
console.log(doc.id, '=>', doc.data());
});
I get the error in the title. Why do they share a code that doesn't work or am I missed something? Thank you!
You need a async
function in order to use the await
keyword.
If you don't have a function in wich this code is ran you can use an IIFE wrapper
(async ()=>{
const productsRef = db.collection('products');
const snapshot = await productsRef.get();
snapshot.forEach(doc => {
console.log(doc.id, '=>', doc.data());
});
})();
or don't use await at all and handle it into the then
chain :
const productsRef = db.collection('products');
const snapshot = productsRef.get().then((snapshot)=>{
snapshot.forEach(doc => {
console.log(doc.id, '=>', doc.data());
});
});
The await
keyword is used for consuming promises, along with async
. But in order for await to work you must wrap it inside a function declared with the async
keyword, like so:
const getProducts = async () => {
const productsRef = db.collection('products');
const snapshot = await productsRef.get();
snapshot.forEach(doc => {
console.log(doc.id, '=>', doc.data());
});
}
getProducts();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.