Using Promise.all for multiple function calls

I have several functions set up like this:

private async p1(): Promise<Result> {
    let p1;
    // Do some operations.

    return p1;
}

private async p5(): Promise<void> {
    // Make a call to an external API.

}

Some of these functions contain a return, while others do not. Each function serves a specific purpose and operates independently.

I am attempting to execute all of these functions asynchronously using Promise.all() to run them in parallel with fast fail-safe capability. In total, I have around 15 function calls arranged as shown in the snippet below:

    let [x1, x2, x3] = await Promise.all([
        this.p1,
        this.p2,
        this.p3,
        this.p4,
        this.p5,
        this.p6,
        this.p7,
        this.p8,
        ...
        this.p15
    ]);

However, when attempting this setup, I encounter the following error message:

src/app/view-models/index.ts:69:37 - error TS2345: Argument of type '(Promise<void> | Promise<Result>)[]' is not assignable to parameter of type 'Iterable<void | PromiseLike<void>>'.
  (Details of error message omitted for brevity)

If I reduce the number of function calls to just 11 or less, everything works fine without any errors. But adding the 12th function call triggers the mentioned error. Is there a solution to this issue that I might be overlooking?

Answer №1

Upon reaching 11 elements, I was able to replicate this issue. The standard header lib.es2015.promise.d.ts contains up to 10 overloads, but according to Bergi's insight, when you hit 11 elements, it assumes the list items are all the same.

Instead of nesting Promise.all, you have the option to specify a generic type for the return values as unknown. While this means you won't be able to perform meaningful operations on the list elements, it shouldn't matter unless you specifically need to extract certain Results from the list.

// bar is of type Promise<unknown[]>
let bar = Promise.all<unknown>([foo1(), foo2(), foo3(), foo4(), foo5(),
    foo6(), foo7(), foo8(), foo9(), foo10(), foo11(), foo12(), foo13(),
    foo14(), foo15()]);

typescript playground

Answer №2

It appears that tuple types are limited to supporting up to twelve elements, as indicated by the overload declarations of Promise.all. In cases where more than twelve elements need to be processed, a workaround involves nesting the Promise.all structure:

let [x1, x2, x3, _] = await Promise.all([
    this.p1,
    this.p2,
    this.p3,
    Promise.all([
        this.p4,
        this.p5,
        this.p6,
        this.p7,
        this.p8,
        ...
        this.p15
    ]),
]);

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

What is the best way to leverage the Nextjs Link tag while also incorporating the data-dismiss attribute?

Currently, I am working on a Next.js project. In the mobile view, my navigation menu utilizes a modal to toggle the navbar. However, I have encountered an issue where when I click on a navigation link, the data gets dismissed but the link itself does not n ...

Tips for validating Enum Strings using the newest version of Joi?

Is there a way to validate Enum String? In the past, I followed this advice from: https://github.com/hapijs/joi/issues/1449 enum UserRole { Admin = 'admin', Staff = 'staff' } const validator = { create: Joi.object().keys({ ...

How does a brand new installation of VSCode believe it comes pre-equipped with TypeScript capabilities?

Operating on Windows 10 Enterprise, After investing several hours and experimenting on various VMs, Interesting Observation #1 Upon opening a .ts file in vscode, it appears to be recognized as TypeScript 2.3.4 as per the screenshot provided below: http ...

Change a nested for-loop into an Observable that has been transformed using RxJS

Currently, the following function is operational, but I consider it a temporary solution as I'm extracting .value from a BehaviorSubject instead of maintaining it as an observable. Existing Code Snippet get ActiveBikeFilters(): any { const upd ...

Error: The variable "dispatcher.useMemo" is not recognized as an object

I encountered an issue while trying to incorporate InversifyJS with MobX in my React Native project. The error message I received was: ERROR TypeError: null is not an object (evaluating 'dispatcher.useMemo') Surprisingly, I have not utilized ...

Tips for Validating Radio Buttons in Angular Reactive Forms and Displaying Error Messages upon Submission

Objective: Ensure that the radio buttons are mandatory. Challenge: The element mat-error and its content are being displayed immediately, even before the form is submitted. It should only show up when the user tries to submit the form. I attempted to use ...

Unable to reach the margin-left properties of the elements

I am facing an issue in accessing the current margin-left CSS property of the class .circle in the code snippet below. A demonstration of this problem can be found on a website called PLUNKr. The reason I need to access this property is because I have to ...

Unexpected Data Displayed by Material UI Modal Component

I'm currently facing an issue with my Material UI Modal component in a React/Typescript project. When a card element is clicked on the site, it should display expanded information in a modal view. However, clicking on any card only shows the most rece ...

An issue has arisen with the TypeScript function classes within the React Class, causing a compile error to be thrown

I am currently in the process of transitioning a React object from being a function to a class. This change is necessary in order to save the state and bind specific functions that I intend to pass to child components. Unfortunately, during compilation, I ...

Is it possible to spread an empty array in JavaScript?

Whenever I run the code below, I encounter the error message Uncaught SyntaxError: expected expression, got '...': [1,2,3, (true ? 4 : ...[])] I'm wondering if spreading an empty array in that manner is allowed? ...

Determining the name of the currently focused DOM element in Angular2

How can I detect the name of a selected element from a group of select elements on a page? For example: <select (click)="functionDetectName()" name="test1"> <select (click)="functionDetectName()" name="test2"> <select (click)="functionDete ...

Interactive Angular Interfaces Featuring Numerous Numeric Choices Within the Main Object

I am currently in the process of designing an interface for my Angular project that allows users to search for video games using the WhatToPlay API within RapidAPI. When a user searches for details on a video game, the result will return a game identified ...

Sending SMS from an Angular application to mobile devices can be achieved through several methods

Does anyone have experience sending SMS from an Angular6 web application? I would appreciate any guidance, such as reference links or code samples. Thank you! ...

Properties cannot be accessed using the standard method in the controller; however, they function correctly when using an arrow

Currently, I am facing a challenge where traditional class methods do not allow me to access the userService. I aim to write typical class methods in my user controller like this: public async register(req: Request, res: Response, next: NextFunction): Pr ...

What are the best practices for utilizing the Express router efficiently?

When building a TypeScript REST API, is there any difference between router.get(); router.post(); router.patch(); router.delete(); ---------------- app.use(); app.use(); app.set(); and router .get() .post() .patch() .delete(); ---------- ...

Tips for effortlessly incorporating a new chip while maintaining a neat arrangement and ensuring button alignment

I am looking to enhance my website by adding chips with new tags in a neatly organized manner. Specifically, I want each new chip to be positioned next to the previous one and have the add-button shift to the right side, always staying in front of the last ...

Struggling to get Tailwind typography to play nice with a multi-column React application shell

I'm currently working on a React application with TypeScript and trying to integrate one of Tailwind's multi-column application shells (this specific one). I want to render some HTML content using Tailwind Typography by utilizing the prose class. ...

Refreshing local storage memory on render with a custom Next.js hook

I recently developed a custom Next.js hook named useLocalStorage to store data in local storage. Everything is working fine, except for one issue - the local storage memory gets refreshed with every render. Is there a way to prevent this from happening? ...

Is there a way for me to access the user's gender and birthday following their login using their Google account details?

I have successfully implemented a Google sign-in button in my Angular application following the example provided in Display the Sign In With Google button: <div id="g_id_onload" class="mt-3" data-client_id="XXXXXXXXXXXX-XX ...

The AuthGuard (Guard decorator) is unable to resolve its dependencies according to Nest

My AuthGuard is responsible for checking the JWT token in controllers. I am trying to use this Guard in controllers to verify authentication, but I encountered the following error: Nest cannot resolve dependencies of the AuthGuard (?, +). Please ensur ...