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

Remove all input fields within an HTML file using a TypeScript method implemented in an Angular 2 component

Within my Angular project, there are several input elements in the HTML file that are not enclosed within a form tag. I am looking to create a function in the TypeScript file that will clear all of these inputs. I attempted to utilize ViewChild, but it a ...

Utilizing TypeScript in a browser with a .NetCore WebApplication

After going through numerous articles, I have not been successful in finding a solution. My challenge lies with a .net core WebApplication that utilizes typescript code instead of javascript. Here are the specific requirements: I need to be able to debu ...

Can a ternary operator be used within an index type query when extending a partial type?

Can anyone provide a detailed explanation of the process unfolding in this snippet? I'm having trouble grasping how this code leads to a type declaration. type ModalErrors = Partial< { [key in keyof InputGroup]: InputGroup[key] extends Speci ...

Is it possible to exclude a certain prop from a styled component that has emotions?

Within my code, there exists a component called BoxWithAs, which is defined as follows: const BoxWithAs = styled.div( { WebkitFontSmoothing: 'antialiased', MozOsxFontSmoothing: 'grayscale' // And more … } ); Everythin ...

I'm unable to modify the text within my child component - what's the reason behind this limitation?

I created a Single File Component to display something, here is the code <template> <el-link type="primary" @click="test()" >{{this.contentShow}}</el-link> </template> <script lang="ts"> imp ...

What is the reason for TypeScript not displaying a type mismatch error in this particular instance?

After starting to use React with TypeScript, I defined my types as follows: type CardInfo = { cardIndex: null | number; title: string; note: string; _id: string; from: string; cardId: string; }; type ContentType = { title: string; note: st ...

In terms of function efficiency, what yields better results: using conditional execution or employing conditional exit?

Feedback is welcomed on the efficiency of the following JavaScript/TypeScript solutions: function whatever(param) { if (param === x) { doStuff(); } } or function whatever(param) { if (param !== x) { return false; } doStuff(); } The se ...

Utilizing Typescript to Inject Generics and Retrieve the Name of an ES6 Module

I am currently working on developing a versatile repository using: Typescript ES6 Angular 1.x However, I am facing challenges in determining the correct way to inject the Entity and retrieve its module name. The main reason for needing the name: I adh ...

Unable to find module 'child_process'

Here is the content of my main.ts file: import { enableProdMode } from '@angular/core'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { environment } from './environments/environment'; if ...

Fixing the forwardRef issue with react-router-dom and material-ui

Despite implementing the forwardRef as recommended in various posts and Material-UI website examples, I am still encountering a warning in the console that has me puzzled. I am working on setting up a drawer with a list of items that are React Router link ...

The dynamic duo of Typescript and Express creates an unbreakable bond within a configuration

Trying to incorporate ES6 modules into my app has been a bit frustrating. Initially, I attempted setting "module": "es2020" or "module": "esnext", only to encounter an error instructing me to specify "type": "module" in the package.json file or use the .m ...

Adding TypeScript to your Vue 3 and Vite project: A step-by-step guide

After setting up my project by installing Vue and Vite using the create-vite-app module, I decided to update all the packages generated by 'init vite-app' to the latest RC versions for both Vue and Vite. Now, I am interested in using TypeScript ...

Guide on how to create a custom response using class-validator in NestJS

Is it feasible to customize the error response generated by class-validator in NestJs? The default error message structure in NestJS looks like this: { "statusCode": 400, "error": "Bad Request", "message": [ { "target": {} ...

ngFor filter based on user input

I am working on a 2-step stepper feature where I need to filter the values in my amountArray based on the age of the person. If the person is above 50 years old, display only the values 10000 and 15000. For Euro currency, show values 25000 and 50000. I att ...

How can we update the information in the initial observable using data from a separate observable, taking into consideration specific conditions in Angular with RxJS?

Encountered a scenario where I need to fetch data from an API (e.g. cars via getCars()) that returns Observables and then get additional data by car model (e.g. features via getFeatures(model)) in order to replace the features data for each car. In relati ...

Encountering tsconfig.json issues following the integration of Tailwindcss v3 into Next.js (create-next-app --typescipt)

Upon opening my code in VS Code, I encountered the following error: Cannot find type definition file for 'accepts'. The file is in the program because: Entry point for implicit type library 'accepts' In an attempt to resolve this issue ...

Comprehensive compilation of Typescript error codes along with solutions

Where can I find a comprehensive list of Typescript error codes and their corresponding fixes? I frequently encounter errors during compilation, such as: data_loader_service.ts(10,13): error TS1005: '=>' expected. data_loader_service.ts(10,24 ...

Is it recommended to keep Angular properties private and only access them through methods?

I'm starting to get a bit confused with Angular/Typescripting. I originally believed that properties should be kept private to prevent external alteration of their values. Take this example: export class Foo{ private _bar: string; constructor(pr ...

Utilizing d3 Charts in Angular 4 Framework

I need assistance with integrating a bar chart in an Angular 4 project, which includes HTML and TypeScript files as components. Can someone please provide guidance on this? The bar chart should show the increase in the number of employees each month, star ...

Tips for referencing all parameters except the last one in TypeScript

Looking for a solution similar to: how to reference all parameters except first in typescript This time, I need to access all parameters except the last one. The solution provided in that question didn't work for my specific case. Any suggestions o ...