【发布时间】:2020-12-07 06:37:10
【问题描述】:
在我的功能中,我有: 2个全局变量, 1个主要入口点异步功能, 1 个异步函数调用 3 个其他异步函数
export const populateWhatsNew = functions.region('asia-east2').https.onCall((populateWhatsNewData,
context) => {
//global variables
const interestedPeople: InterestedPerson[] = []
const whatsNewObjects: WhatsNewObject[] = []
//executing the main entry point function
return getTopInterestedPeopleAndTheirData()
//the entry point main function
async function getTopInterestedPeopleAndTheirData() {
//this function queries multiple documents fromn firestore and adds it to interestedPeople
//then calls an async function
async getTheData(interestedPeople)
}
async function getTheData(theInterestedPeople: InterestedPerson[]) {
//I want these 3 tasks in the array to be executed sequentially but
//the order is mixed
const tasks = [
getCompsReceived(theInterestedPeople),
getTheLatestInsights(theInterestedPeople),
checkIfWhatsNewObjectsAreSufficient()
]
for await (const task of tasks) {
return task
}
}
async function getCompsReceived(theInterestedPeople: InterestedPerson[]) {
//queries documents from firestore and pushes it to whatsNewObjects
}
async function getTheLatestInsights(theInterestedPeople: InterestedPerson[]) {
//queries documents from firestore and pushes it to whatsNewObjects
theInterestedPeople.forEach(async (person) => {
//loop through each array to get some data
}
}
async function checkIfWhatsNewObjectsAreSufficient() {
//just checks the length whatsNewObjects and if less than 80 re runs the loop
//else adds this the data in the array to firestore and then calls
if ( whatsNewObjects.lenth > 80 ) {
//pushes all the data in whatsNewObjects to Firestore and then
//calls another async function
await incrementsTheTotalNoItemsAndUnReadItems()
}
}
async function incrementsTheTotalNoItemsAndUnReadItems() {
//increments some number fields in firestore by the
//length of the WhatsNewObjectsLength
}
})
所以我希望函数按顺序执行。但我注意到函数的顺序是混合的。如何实现get data()方法中3个函数的顺序执行
【问题讨论】:
-
应该是
for (const task of tasks) await task,你使用for await是错误的。此外,您的示例包含您需要修复的语法错误 -
感谢Aluan,已解决此问题,问题出在Array中这3个任务的函数体以及您发现的问题
-
Anudeep Ananth@ 很高兴您解决了这个问题。请考虑将解决方案作为答案发布,以使其可见以供将来参考。
标签: typescript firebase async-await google-cloud-functions