Comparing TypeORM promise.all to await when searching

While researching ways to optimize database searches, I came across promise.all which has the potential to speed up the process.

My approach involves conducting searches through three functions. The tables consist of various joins, with instances where the same table needs to be queried multiple times.

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 provided code is structured as described above. I am curious if running the following code in the controller would impact the speed:

const [a,b,c] = await Promise.all([
  this.service.methodA(),   
  this.service.methodB(),
  this.service.methodC()]);

In my current implementation, the time taken is approximately 1 second without utilizing promise.all and around 0.8-0.9 seconds when using it.

Assessing any additional effects from this optimization has proven challenging. Despite my research efforts, I have not found a definitive answer regarding whether there can be further improvements in speed, especially when querying the same table repeatedly.

I eagerly await your response. Thank you.

Answer №1

In theory, the process should be quicker. However, it's important to keep in mind that TypeOrm limits the default connection pool to 10. This means that if methodA creates 10 connections, other methods will have to wait for them to complete. The same applies if methodB is dealing with open requests - causing delays for requests in methodC and beyond. In these situations, the code may appear more synchronous in the final example, but there should still be an overall speed improvement.

Answer №2

My response is intended for asynchronous calls in general, but it should also be relevant to your specific situation.

When you choose to utilize promise chaining or await, you are essentially pausing until a certain operation completes before moving forward. On the other hand, employing methods like promise.all() or promise.allSettled() means that you are initiating all operations simultaneously. It's safe to say that using promise.all or promise.allSettled() typically yields faster execution speeds in most scenarios.

However, the decision of whether to use these methods will largely depend on your application. If your asynchronous calls have dependencies between them, it would be best to stick with promise chaining or await. But if not, then utilizing other methods could be more suitable.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it necessary to enforce a check for surplus properties in the return type of a function

In this particular scenario, the TypeScript compiler does not raise an error when a function returns an object with the type UserProfile even though the expected return type is UserProfileWithNoPermissions. Here's an example: interface UserProfile { ...

What methods can I use to establish communication with other clients connected to a MySQL server through Python?

I am managing multiple computers that are running Python applications and all connected to the same MySQL server. Each application has a tkinter GUI for editing a specific set of data linked to a table in the MySQL server. Whenever one machine updates its ...

Guide to setting data types for [key, value] pairs within a forEach iteration

I am currently encountering a typescript syntax error in my project that is indicating the need to define the prodStatus variable... const products = { 1: {isUpdating: false, qty: 2}, 2: {isUpdating: true, qty: 4} } const updatingProducts: Array< ...

PHP fails to return any data when JSON data is not decoded

After fetching json data from a blob field in my MySQL database and using the Laravel framework, everything seems to be functioning correctly. However, I am encountering an issue where the JSON data retrieved from the blob field is not being decoded prop ...

Place the Div in a consistent position on images of varying widths

I have a dilemma with my class that is supposed to display images. The issue arises when I try to place a div within an image inside this class. Everything works smoothly when the image takes up the entire width of the class, but as soon as the image widt ...

Ways to mandate a field to only be of type object in TypeScript

I need to design a type that includes one mandatory property and allows for any additional properties. For instance, I require all objects to have an _id property of type string. {_id: "123"} // This will meet the criteria {a: 1} // This will not work as i ...

The error message UnhandledPromiseRejectionWarning is triggered due to a TypeError stating that the function authenticate is

Currently, I am attempting to incorporate basic authentication into my API project using Knex, Express, and MySQL. Here are the functions I have implemented: const users = [{ id:1, username:'selia', password:'fullservice'}] functio ...

Is there a way to set a table column to a value from a different table column by using two other columns as criteria?

Greetings everyone, how are you all doing today? I'm facing a challenge while trying to write a small script and I can't seem to figure out why it's not working. My thought process is as follows: Update all instances of tech_kunena_message ...

Incorporating data from a MySQL database into a PHP page using a variable included in the URL

I am currently working on designing a website and one of the features I would like to implement is the ability to create unique URLs for users. My goal is to have the URL structured as follows: http://www.example.com/page.php?user_id=3 Each user would ha ...

Guide on executing a method once a response is received from a previously called method

I am currently attempting to upload an array of files to a spring boot server. The issue I am facing is that each file is being saved one at a time. I am using a for loop to iterate through the file array and making a request for each file to be saved. H ...

Does MySQL have a feature to filter data sets?

I am working with a database that consists of two tables - users and messages. Both tables contain records for multiple companies. I need to include companyNo=$companyNo in all queries, such as select * from users where companyNo=$_SESSION['comp ...

The new PropTypes package is incompatible with TypeScript's React context functionality

When utilizing React.PropTypes, the code functions correctly but triggers a warning about deprecation (Accessing PropTypes via the main React package is deprecated...): import * as React from 'react'; export class BackButton extends React.Compo ...

Skip over any null values in Angular

As someone new to Angular, I have a function in a component that makes API calls and expects results, but errors can also occur. this.Service.callAPI(). .subscribe(data => { if(data?.errors){ }); The issue is arising because both ...

Can you explain why it prints to the console twice every time I try to add an item?

This is a note-taking application created using Angular and Firebase. The primary functionalities include adding items and displaying them. I noticed a strange behavior where my ngOnInit() method is being called twice every time I add an item. As shown in ...

What could be causing the unexpected behavior of TypeScript in Visual Studio Code?

VSCode is showing errors, but everything is functioning properly. Here are some of the errors: Type expected. [ { "resource": "/C:/Users/Dell/Desktop/vite-project/src/App.tsx", "owner": "typescript", "code": "1110", "se ...

Exploring the power of NodeJS 8.x with EventEmitter and the efficiency of async/

Is it possible to use async functions with an event emitter? Some sources advise against it, but I am interested in incorporating async functionality with the event emitter to handle messages. Below is the code snippet I have been working on: server.on(& ...

How can I access other properties of the createMuiTheme function within the theme.ts file in Material UI?

When including a theme in the filename.style.ts file like this: import theme from 'common/theme'; I can access various properties, such as: theme.breakpoints.down('md') I am attempting to reference the same property within the theme ...

Enhancing slugs with .htaccess

Currently, I am in the process of constructing a REST API using PHP. I have successfully implemented slugs for the most part. For example, when I request /api/admin/v1/users/1, it returns the necessary user data. However, I also need to be able to extend ...

Ways to execute an Update Query instead of an Insert when using Count(1)

I need to modify the following SQL query to update instead of insert in order to handle duplicates: UPDATE test_reports SET Total_Count = (SELECT COUNT(*) FROM table1 WHERE location = 'West Midlands') WHERE Table_Name = 'West Midlands' ...

What are the top PHP functions for safeguarding input against SQL injection and how can they be implemented effectively?

Similar Question: Best method for preventing SQL Injection in PHP Protecting against MySQL injection and identifying vulnerabilities using PHP Hello, I recently inquired about the vulnerability of my code to SQL injection. Here is the code I used: ...