Should one bother utilizing Promise.all within the context of a TypeORM transaction?

Using TypeORM to perform two operations in a single transaction with no specified order. Will utilizing Promise.all result in faster processing, or do the commands wait internally regardless?

Is there any discernible difference in efficiency between the two options?

// Option 1
getManager().transaction(async manager => {
  await Promise.all([
    manager.insert(...),
    manager.update(...),
  ]);
});;

// Option 2
getManager().transaction(async manager => {
  await manager.insert(...);
  await manager.update(...);
});

To clarify, I am aware of how Promise.all can enhance performance in JavaScript overall due to its single-threaded nature and event loop mechanics. However, my inquiry pertains specifically to the behavior of multiple queries within the same transactional manager in TypeORM, as they appear to execute sequentially whether Promise.all is used or not.

Answer №1

When dealing with concurrent transactions in Typeorm, using Promise.all may lead to incorrect behavior due to the fact that it doesn't wait for all promise results to complete.

await Promise.all(tenDbTxns);

// 5 out of 10 fulfilled
// 6 rejected ---> typeorm rollback 6 out of 10
// 4 pending and will be committed after fulfillment

To address this issue, consider the following solutions:

  1. Execute queries sequentially:
const data = [];
for (const tx of tenDbTxns) {
    const res = await tx;

    data.push(tx);
}
  1. Concurrent execution using Promise.allSettled which waits for all promise results:
const settled = await Promise.allSettled(tenDbTxns);
const data = [];
for (const res of settled) {
    if (res.status === 'rejected') {
        throw res.reason;
    }

    data.push(res.value);
}

Answer №2

TypeORM streamlines your query creation process by generating queries for you, ultimately simplifying database interactions. For instance, when performing two separate actions on the database, it typically results in two queries being executed. Take, for example, creating a new customer and generating an invoice record. Utilizing promise all can help expedite this process, but it is essential to ensure that there are no interdependencies between the requests.

For instance, if creating an invoice requires information from a previously created customer, it's crucial to manage these dependencies effectively. However, with independent requests, promise all can be leveraged to execute multiple queries simultaneously. Afterward, you can verify the success of each request before committing the transaction or rolling it back accordingly.

I trust you will find this approach beneficial. If you have additional queries or require further assistance, kindly provide more context so I can offer tailored support.

Answer №3

There is an issue with TypeOrm not functioning correctly when using promise.all and transactions (https://github.com/typeorm/typeorm/issues/1014). While using promise all may increase speed, transactions may not work as expected.

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

Unable to declare a string enum in TypeScript because string is not compatible

enum Animal { animal1 = 'animal1', animal2 = 'animal2', animal3 = 'animal3', animal4 = 'animal4', animal5 = 'animal5' } const species: Animal = 'animal' + num Why does typescr ...

A convenient utility for generating React components with pre-populated Tailwind CSS classes

When it comes to extracting local Tailwind-styled components, I tend to do it like this: const Container: React.FC = ({ children }) => ( <div className="bg-white px-5 py-5"> {children} </div> ); To simplify this process, I ...

Is there a method for verifying the application signature in Ionic?

For the past 2 days, I've been on a quest to find information about app certificate validation libraries/functions in Ionic. After discovering SignatureCheck.java for Android (link: enter link description here), I wonder if there is a similar solution ...

Angular2 Navigation Menu

I have a side bar and I want its children to appear when the user clicks on the parent. For example, clicking on LinkTest should display its corresponding content as block. You can check out the Angular and Typescript code snippet at this link: http://jsfi ...

Angular TSLint: Proceed to the following stage despite any encountered errors

I'm facing issues with TSLint in my Azure Devops Build Pipeline. Despite encountering lint errors, I need the build pipeline to proceed to the next step. How can I achieve this? Command Line: - script: | npm run lint > tsLintReport.txt ...

Error: Incorrect data type found in React Route component

I've encountered an issue while attempting to utilize the Route component in my application. The error message I'm receiving reads as follows: [ts] Type '{ path: "/:shortname"; component: typeof FirstComponent; }' is not assignable ...

Tips for integrating a variety of components onto a single webpage

Exploring the functionality of Angular, I am looking to include multiple components on a single page. How can this be achieved effectively in Angular? I envision each div representing a distinct component and view, with all components residing in separate ...

Improprove the performance of an array of objects using JavaScript

Hello there, I am currently in the process of creating an array. this.data = [{ label: 'Total', count: details.request.length, }, { label: 'In-Progress', count: details.request.filter((obj) => obj.statusId === 0 || ob ...

What could be causing the module to break when my Angular service, which includes the httpClient, is added in the constructor?

After creating a backend RESTful API, I encountered difficulties while trying to access it. To address this issue, I developed a database-connection.service specifically for making POST requests. However, I am facing challenges in implementing this solut ...

Error: The jasmine framework is unable to locate the window object

Currently, I am testing a method that includes locking the orientation of the screen as one of its functionalities. However, when using Jasmine, I encountered an error at the following line: (<any>window).screen.orientation.lock('portrait&apos ...

Verify the validity of an image URL

I am attempting to create a function in TypeScript that checks the validity of an image source URL. If the URL is valid, I want to display the image using React Native Image. If the URL is invalid, I would like to replace it with a local placeholder imag ...

Error in Typescript syntax within a CommonJS/Node module: Unexpected colon token found in function parameter

After validating the file with TS, there are no more errors. However, during runtime, I encounter an "Unexpected token ':'" error on any of the specified TS, such as immediately erroring on function (err: string). The following are my build and ...

After upgrading from Angular 7 to 12, the module './rest.service.interface' does not export 'RestService' (imported as 'RestService'), causing it to not be found

Hey everyone, I've been struggling with a problem for hours now and I can't seem to fix it. Here is the interface I'm working with: import { HttpClient } from '@angular/common/http'; import { Response } from '@angular/http&apo ...

Error message: Missing "@nestjs/platform-express" package when performing end-to-end testing on NestJS using Fastify

Just set up a new NestJS application using Fastify. While attempting to run npm run test:e2e, I encountered the following error message: [Nest] 14894 - 11/19/2021, 10:29:10 PM [ExceptionHandler] The "@nestjs/platform-express" package is missi ...

I am eager to perform DOM manipulation similar to jQuery but within the context of Angular 6

Is there a way to modify the background color of the main div when a button is clicked? <div> <p>I'd like to be able to change the background color of the parent div by clicking a certain button. </p> <button (click)=" ...

What is the method for obtaining a literal type through a function parameter to use as a computed property name?

Can you help me with this code snippet? const fn = (name: string) => { return { [name]: "some txt" }; }; const res = fn("books"); // books or any other string The type of res recognized by TS is: const res: { [x: string]: string ...

When attempting to fetch JSON data using the Angular 2 `http.get()` method, the data returned is undefined and the component does not reflect any

My http-data.service is set up to accept json for output in the component template. Initially, the console displays that the first few calls return undefined, while subsequent calls start returning json. However, upon checking the component, it is evident ...

What is the best way to incorporate a string value from an external file into a variable in TypeScript without compromising the integrity of special characters?

I am encountering an issue with importing a variable from a separate file .ts that contains special characters, such as accents used in languages like French and Spanish. The problem I am facing is that when I require the file, the special characters are ...

Exploring the functionality of angular reactive forms in creating intricate JSON structures

After numerous attempts to resolve the issue on my own, I am reaching out to an Angular developer for assistance. My goal is to display a JSON object in the UI: Here is the JSON Object : items={"departure":"New York","arrival":"California","stations":[ ...

Why does the entire page in Next.JS get updated whenever I switch pages?

Currently, I am utilizing Next.JS to create a single-page application website in React. I have successfully set up routing (https://nextjs.org/docs/routing/dynamic-routes) In addition, I have also configured Layouts (https://nextjs.org/docs/basic-features ...