I found promise.all while studying to speed up database search.
I proceed with the search through three functions. Many tables are made up of join, and sometimes the same table is looked up.
async methodA(){
const [result1, result2] = await promise.all([
this.Arepository.find({relation:[...],where:{...}},
this.Brepository.find({relation:[...],where:{...}})
]);
for(const r of result1){
r.user = await this.usersRepository.findOne({id:r.user_id}}
}
return ...
}
async methodB(){
const [result1, result2] = await promise.all([
this.Brepository.find({relation:[...],where:{...}},
this.Crepository.find({relation:[...],where:{...}})
]);
for(const r of result1){
r.user = await this.usersRepository.findOne({id:r.user_id}}
}
return ...
}
async methodC(){
const [result1, result2] = await promise.all([
this.Arepository.find({relation:[...],where:{...}},
this.Crepository.find({relation:[...],where:{...}})
]);
for(const r of result1){
r.user = await this.usersRepository.findOne({id:r.user_id}}
}
return ...
}
The code is written as above. If I run the code below in the controller, will the speed be affected?
const [a,b,c] = await Promise.all([
this.service.methodA(),
this.service.methodB(),
this.service.methodC()]);
Currently, in my code, 1 second if promise.all does not exist, 0.8-0.9 seconds if there is.
It is difficult to determine if this has any other effect.
So I did a search, but couldn't help but get an ambiguous answer. I wonder if the speed can be even a little bit faster in this case, even if look up the same table.
I look forward to your reply. thank you.
CodePudding user response:
Theoretically it should be faster. However, we must not forget that TypeOrm
has a max default connection pool of 10, meaning that if methodA
creates 10 connections, the other methods will have to wait for them to finish. This is also true if methodB
has open requests - which will hold up the requests in methodC
and so on. In these scenarios the code in the parent (last) example does act more synchronous, but there should be speedup nevertheless.
CodePudding user response:
I am answering this in general for asynchronous calls and should be applicable to your case as well.
If you opt to use promise chaining or await
, you are essentially waiting for some operation to be done with and only then move on. But when you use something like promise.all()
or promise.allSettled()
it means that you are not waiting for any particular operation, it's as good as starting all those operations in parallel. It's easy to conclude that using promise.all
or promise.allSettled()
would result in better execution speeds in nearly all cases.
However whether to use it or not would highly depend on your application. If you have asynchronous calls where there is a dependency between them, you are better off using promise chaining or await
, if not then you could use others.