[英]await is only valid in async function in nodejs
I have a built an app with flutter + firebase, I need to delete document if it was create more than 5 hours ago so I built a script with nodejs.我用 flutter + firebase 构建了一个应用程序,如果文档是在 5 个多小时前创建的,我需要删除它,所以我用 nodejs 构建了一个脚本。 The problem is that documents are not deleted because I don't wait the delete function to finsh.问题是文档没有被删除,因为我不等待删除 function 来完成。 So I tried to add async/await but I have an error.所以我尝试添加 async/await 但我有一个错误。
I tried to do this:我试图这样做:
async function mydelete(){
let getDoc = cityRef.get()
.then(snapshot => {
snapshot.forEach(doc => {
docid = doc.id;
if (doc.id.length == 4)
db.collection('collection').doc(doc.id).delete();
else if (doc.data().Timestamp._seconds < new Date() - 18000) {
console.log(doc.id)
a = await db.collection('collection').doc(doc.id).delete()
}
else console.log('false')
})
})
.catch(err => {
console.log('Error getting documents', err);
});
} }
But now I have this error: SyntaxError: await is only valid in async function但现在我有这个错误: SyntaxError: await is only valid in async function
You can not use await
without async
keyword in any function including callback function also.您不能在任何 function 包括回调 function 中使用没有async
关键字的await
。 So snapshot.forEach(doc => {...}) should be: snapshot.forEach(async doc => {...})
所以snapshot.forEach(doc => {...}) should be: snapshot.forEach(async doc => {...})
error: SyntaxError: await is only valid in an
async
function错误:语法错误:等待仅在async
function 中有效
To be able to use await inside the function the syntax always must be like below为了能够在 function 中使用 await ,语法必须如下所示
async function () {
await functionReturnsPromise()
}
The below code is wrong you will get above error:下面的代码是错误的,你会得到上面的错误:
async function () {
functionTest(()=>{
await functionReturnsPromise()
})
}
We will have to put async
keyword before the callback function to be able to run the code as below我们必须在回调 function 之前放置async
关键字才能运行如下代码
async function () {
functionTest( async ()=>{
await functionReturnsPromise()
})
Change your code something like below:更改您的代码,如下所示:
async function mydelete() {
try {
let snapshot = await cityRef.get()
snapshot.forEach(async (doc) => {
let docid = doc.id;
if (doc.id.length == 4)
await db.collection('collection').doc(doc.id).delete();
else if (doc.data().Timestamp._seconds < new Date() - 18000) {
console.log(doc.id)
let a = await db.collection('collection').doc(doc.id).delete()
} else console.log('false')
})
}
catch (err) {
// handle error here
}
}
Note: there might be a syntax error in code in the above code注意:以上代码中的代码可能存在语法错误
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.