gpt4 book ai didi

javascript - 如何在云函数的循环内设置await表达式?

转载 作者:行者123 更新时间:2023-12-01 00:22:03 24 4
gpt4 key购买 nike

这是我的 firebase 云函数的简化代码:

const admin = require("../utilities/firebase_admin_init")
const db = admin.firestore()

exports.cronDeactivatingExpiredEvents = functions.https.onRequest(async (request,response) => {


const now = new Date()
const oneMonthAgo = moment().subtract(1,"month").toDate()


try {
const expiredEventsSnapshot = await eventRef
.where("isActive","==",true)
.where("hasBeenApproved","==",true)
.where("dateTimeStart",">",oneMonthAgo)
.where("dateTimeStart","<",now)
.get()


const expiredEventIDs = [] // list of IDs here ....


// prepare promises to delete event data in user 'attendedEvents' subcollection.
const deleteAttendedEventsDataPromises = []

for (const eventID of expiredEventIDs) {

const eventAttendeeSnapshot = await db.collection("events").doc(eventID).collection("Attendee").get()
const attendeeDocuments = eventAttendeeSnapshot.docs

// getting all attendeeIDs.
const attendeeIDs = []

attendeeDocuments.forEach( attendeeSnapshot => {
const attendee = attendeeSnapshot.data()
attendeeIDs.push(attendee.uid)
})

attendeeIDs.forEach( attendeeID => {
const p = db.collection("users").doc(attendeeID).collection("attendedEvents").doc(eventID).delete()
deleteAttendedEventsDataPromises.push(p)
})

}

// delete event data in user 'attendedEvents' subcollection
await Promise.all(deleteAttendedEventsDataPromises)
console.log(`successfully delete all events data in all attendee user subcollection`)


response.status(200).send(`sucess`)

} catch (error) {
response.status(500).send(error)
}



})

正如你在上面看到的,循环中有一个await表达式,但是我有一个如下图所示的错误标记,所以我无法部署该函数:

enter image description here

这是我运行firebase部署后出现的错误

enter image description here

/Users/muchammadagunglaksana/Documents/kumpul_muslim/cloud_functions_serverless_backend/functions/service/cron_operations.js 140:43 error Unexpected await inside a loop no-await-in-loop
170:41 error Unexpected await inside a loop no-await-in-loop

✖ 2 problems (2 errors, 0 warnings)

npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! functions@ lint: eslint . npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the functions@ lint script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in: npm ERR!
/Users/muchammadagunglaksana/.npm/_logs/2019-12-14T10_47_36_788Z-debug.log

Error: functions predeploy error: Command terminated with non-zero exit code1

我尝试从这里阅读一些解决方案 Using async/await with a forEach loop 。就像这样使用for wait

enter image description here

确实,红色错误标记会消失,但我仍然无法部署该功能。这是我运行 firebase deploy

后出现的错误

enter image description here

functions[cronDeactivatingExpiredEvents(us-central1)]: Deployment error. Function failed on loading user code. Error message: Code in file index.js can't be loaded. Is there a syntax error in your code? Detailed stack trace: /srv/service/cron_operations.js:138 for await (const eventID of algoliaObjectIDs) { // algoliaObjectIDs is same as expired EventIDs ^^^^^

SyntaxError: Unexpected reserved word at createScript (vm.js:80:10) at Object.runInThisContext (vm.js:139:10) at Module._compile (module.js:617:28) at Object.Module._extensions..js (module.js:664:10) at Module.load (module.js:566:32) at tryModuleLoad (module.js:506:12) at Function.Module._load (module.js:498:3) at Module.require (module.js:597:17) at require (internal/module.js:11:18) at Object. (/srv/index.js:2:24)

在 .eslintrec.json 中我使用:

"parserOptions": {
// Required for certain syntax usages
"ecmaVersion": 2018
},

我是云函数和后端开发的新手。如果我的问题太基本,我很抱歉。

我该怎么办?

最佳答案

第一个错误是关于eslint,有一条规则no-await-in-loop,它不允许在循环中等待,因为操作是串行的,而不是并行的基本上是为了减少资源和时间的浪费。

您可以做的就是像推送 Promises 一样使用它,然后执行 Promise.all ,或者您可以仅禁用该部分的规则。

/* eslint-disable no-await-in-loop */
for (const eventID of expiredEventIDs) {

const eventAttendeeSnapshot = await db.collection("events").doc(eventID).collection("Attendee").get()
const attendeeDocuments = eventAttendeeSnapshot.docs
....
....
}
/* eslint-enable no-await-in-loop */

第二个错误意味着您忘记将 for-await-of 包装在 async function 包装器中OR您正在使用 <强> Node 版本<10

关于javascript - 如何在云函数的循环内设置await表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59334229/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com