[英]Uncaught SyntaxError: await is only valid in async function (FireBase documentation)
I'm trying to get data from my Firestore database.我正在尝试从 Firestore 数据库中获取数据。 Based on Firestore documentation I wrote this:基于Firestore 文档,我写了这个:
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.您需要一个async
函数才能使用await
关键字。
If you don't have a function in wich this code is ran you can use an IIFE wrapper如果您没有运行此代码的函数,您可以使用 IIFE 包装器
(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 :或者根本不使用 await 并将其处理到then
链中:
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
. await
关键字与async
一起用于消费承诺。 But in order for await to work you must wrap it inside a function declared with the async
keyword, like so:但是为了让 await 工作,您必须将它包装在一个用async
关键字声明的函数中,如下所示:
const getProducts = async () => {
const productsRef = db.collection('products');
const snapshot = await productsRef.get();
snapshot.forEach(doc => {
console.log(doc.id, '=>', doc.data());
});
}
getProducts();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.