I have the following function in c# application:
foreach (var p in proglist)
{
programData.GetData1= new List<GetData1_ViewModel>(GetData1(programid, reportingdate));
programData.GetData2= new List<GetData2_ViewModel>(GetData2(programid, reportingdate));
programData.GetData3= new List<GetData3_ViewModel>(GetData3(programid, reportingdate));
programData.GetData4= new List<GetData4_ViewModel>(GetData4(programid, reportingdate));
programData.GetData5= new List<GetData5_ViewModel>(GetData5(programid, reportingdate));
}
I have the same function in a Typescript application:
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")),
]);
}
They both call the same database tables, storedprocedures, etc.
The C# code takes 5 seconds to complete The Typescript code takes 189 seconds to complete
I don't understand why the C# is so much quicker than Typescript. What should I be looking at to speed this up?
CodePudding user response:
If this.GetMeasureForScorecard()
and this.GetData5()
return a Promise
that once resolved will contain the value queried, then you don't need to await
inside Promise.all()
, because you'll be defeating it's purpose, which is to resolve unresolved promises (non-awaited).
for (const p of proglist) {
const [data1, data2, data3, data4, data5] = await Promise.all([
this.GetMeasureForScorecard(p.programId, reportingdate, "GetData1"),
this.GetMeasureForScorecard(p.programId, reportingdate, "GetData2"),
this.GetMeasureForScorecard(p.programId, reportingdate, "GetData3"),
this.GetData4(p.programId, reportingdate, "GetData4"),
this.GetData5(p.programId, reportingdate, "GetData5"),
]);
}
Making multiple functions call with the await
keyword will force the JS interpreter to make sequential calls instead of concurrent calls (or quasi-concurrent), which is what you are looking for (I assume).
await this.GetMeasureForScorecard(p.programId, reportingdate, "GetData1");
// Waits until Promise above is resolved
await this.GetMeasureForScorecard(p.programId, reportingdate, "GetData2"),
// Waits until Promise above is resolved
await this.GetMeasureForScorecard(p.programId, reportingdate, "GetData3"),