Home > Blockchain >  Running Multiple Functions Sequentially Within forEach in TypeScript/JavaScript
Running Multiple Functions Sequentially Within forEach in TypeScript/JavaScript

Time:09-08

I have a forEach where I get an ID and then run 5 different functions using that id. I then take the results of each function and put it in an array. My problem is that the functions don't seem to be running in the correct sequence. This is the code:

   proglist.forEach(async (p) => {
        this.data1 = []
        this.data2 = []
        this.data3 = []
        this.data4 = []
        this.data5 = []
        Promise.all([
        this.data1 = await this.GetMeasureForScorecard(p.programId,reportingdate,'GetData1'),
        this.data2 = await this.GetMeasureForScorecard(p.programId,reportingdate,'GetData2'),
        this.data3 = await this.GetMeasureForScorecard(p.programId,reportingdate,'GetData3'),
        this.data4 = await this.GetData4(p.programId,reportingdate,'GetData4'),
        this.data5 = await this.GetData5(p.programId,reportingdate,'GetData5')]
        )
        ProgramScorecard.push({
            programId: p.programId, 
            programName: p.programName,
            reportingDate: reportingdate,
            data1 : this.data1,
            data2 : this.data2,
            data3 : this.data3,
            data4 : this.data4,
            data5 : this.data5
        });

    });

I want it to get the first program, run the functions, populate the array, then run the next program, etc...

The array does get populated but the data is inaccurate.

It doesn't seem to wait for one program to complete before it runs the next. I know I have an issue with using promises. How can I get this to work properly?

CodePudding user response:

You need to use await with Promise.all since Promise.all returns another promise. You should also use a regular for loop because for loops respect await (unlike forEach).

for (const p of proglist) {
    this.data1 = [];
    this.data2 = [];
    this.data3 = [];
    this.data4 = [];
    this.data5 = [];
    await Promise.all([
        (this.data1 = await this.GetMeasureForScorecard(p.programId, reportingdate, "GetData1")),
        (this.data2 = await this.GetMeasureForScorecard(p.programId, reportingdate, "GetData2")),
        (this.data3 = await this.GetMeasureForScorecard(p.programId, reportingdate, "GetData3")),
        (this.data4 = await this.GetData4(p.programId, reportingdate, "GetData4")),
        (this.data5 = await this.GetData5(p.programId, reportingdate, "GetData5")),
    ]);
    ProgramScorecard.push({
        programId: p.programId,
        programName: p.programName,
        reportingDate: reportingdate,
        data1: this.data1,
        data2: this.data2,
        data3: this.data3,
        data4: this.data4,
        data5: this.data5,
    });
}
  • Related