在Firebase函数中按顺序链式异步函数



在我的函数中,我有: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
}
})

所以我希望函数按顺序执行。但我注意到函数的顺序是混合的。如何在获取数据((方法中实现3个函数的顺序执行

所以,我使用的语法实际上是正确的,问题在于async函数getTheLatestInsights(interestedPeople:InterestedPerson[](在typescript中使用异步函数有一个陷阱,在以下语法中,异步函数内部的数组用于循环:

theInterestedPeople.forEach(async (person) => { 
//loop through each array to get some data
}

实际上不起作用,所以函数基本上会跳过整个循环(但稍后执行(。因此,如果我们想让函数等到整个循环完成后再继续到函数体的剩余部分,那么我们必须使用以下语法:

for (const person of theInterestedPeople) {
//loop through each array to get some data
}

为了确保您的async/await,您需要使用promise来处理代码流。

promise所做的是允许您控制执行一个接一个要执行的异步任务序列。

承诺链接示例:

new Promise(function(resolve, reject) {
setTimeout(() => resolve(1), 1000); // (*)
}).then(function(result) { // (**)
alert(result); // 1
return result * 2;
}).then(function(result) { // (***)
alert(result); // 2
return result * 2;
}).then(function(result) {
alert(result); // 4
return result * 2;
});

请记住,这不是链接承诺的唯一方式。您可以在文档中找到关于">承诺链接";。

相关内容

  • 没有找到相关文章

最新更新