简体   繁体   English

在 Firebase 个函数中顺序链异步函数

[英]Chain async functions sequentially in Firebase functions

In my function I have: 2 global variables, 1 main entry point async function, 1 async function that calls 3 other async functions在我的 function 中,我有:2 个全局变量、1 个主入口点异步 function、1 个调用其他 3 个异步函数的异步 function

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
  }

})

So I want the functions to be executed sequentially.所以我希望函数按顺序执行。 But I have noticed the order of the functions is mixed.但我注意到函数的顺序是混合的。 How do I achieve sequential execution of the 3 functions in the get the data() method如何在get data()方法中实现3个函数的顺序执行

So, The syntax that I used was actually correct, the problem was in the body of the async function getTheLatestInsights(theInterestedPeople: InterestedPerson[]) There is a gotcha for using async functions in typescript where in the following syntax used to loop through an array inside an async function:所以,我使用的语法实际上是正确的,问题出在异步 function 的主体中在异步 function 中:

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

Doesn't actually work, so the function would basically skip the entire loop(but execute it a little later).实际上不起作用,所以 function 基本上会跳过整个循环(但稍后执行)。 So if we want the function to wait till this entire loop is completed before proceeding to the remaining part of the function body then we have to use this syntax:因此,如果我们希望 function 在继续执行 function 主体的剩余部分之前等到整个循环完成,那么我们必须使用以下语法:

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

In order to make sure that your async/await you need to use promises in order to handle the flow of the code.为了确保您的异步/等待您需要使用承诺来处理代码流。

What promises do is allowing you to control to execute a sequence of asynchronous tasks to be performed one after another. promises 的作用是允许您控制执行一系列异步任务,一个接一个地执行。

Example of Promise chaining: 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;

});

Please keep in mind that this is not the only way of chaining promises.请记住,这不是链接承诺的唯一方式。 You may find more information in the documentation about " Promises chaining ".您可以在有关“ Promises chaining ”的文档中找到更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM