如何解决在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
}
})
所以我希望这些功能按顺序执行。但是我注意到功能的顺序是混杂的。如何在get data()方法中实现3个函数的顺序执行
解决方法
所以,我使用的语法实际上是正确的,问题出在 异步函数getTheLatestInsights(theInterestedPeople:InterestedPerson []) 在打字稿中使用异步函数有一个陷阱,其中以下语法用于在异步函数内部遍历数组:
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
}
,
为了确保异步/等待状态,您需要使用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;
});
请记住,这不是链接诺言的唯一方法。您可以在documentation中找到有关“ 承诺链”的更多信息。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。