What is the best way to hold out for a specific number of promises to be fulfilled and halt the resolution of any others

While working in TypeScript, I need to create around 100 instances of Promise. However, I am only interested in waiting for the resolution of 5 of them. Any promises beyond that can either be canceled (if feasible) or rejected since they are no longer required for the task at hand.

What is the best approach to achieve this?

Answer №1

Here is a potential solution that I suggest:

function executeTasks<R>(tasks: Promise<R>[], limit: number) {
    let boundedLimit = Math.min(limit, tasks.length);
    let results: R[] = [];

    return new Promise((resolve, reject) => {
        function onTaskCompletion(result: R) {
            if (results.length === boundedLimit - 1) {
                resolve(results.concat([result]));
            } else {
                results.push(result);
            }
        }
        tasks.forEach(task => task.then(onTaskCompletion).catch(reject));
    })
}

This implementation assumes that all promises in the array return the same type of result. However, you can customize it by passing in a union type, any, or void based on your specific requirements.

The main concept is for each promise to add its result to a shared array. If the current promise fulfills the conditions, the overall promise is resolved using the collective results array. The boundedLimit variable ensures proper handling when a numeric limit is specified, such as passing in an array of 100 promises with a limit of 5.

Regarding cancellation of ES6 promises, from my understanding and research, there isn't a practical method to cancel them, so this aspect has not been addressed in the provided solution.

You may find the structure of the onTaskCompletion function somewhat unconventional. In asynchronous code, I prefer maintaining a single path for modifying shared state to avoid potential complications.

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

Parsing errors occurred when using the ngFor template: Parser identified an unexpected token at a specific column

In my Angular CLI-built application, I have a component with a model named globalModel. This model is populated with user inputs from the previous page and displayed to the user in an HTML table on the current page. Here's how it's done: <inp ...

Material-UI Alert: The property `onKeyboardFocus` for event handling is unrecognized and will not be applied

Here is a more detailed trace of the issue: warning.js:33 Warning: Unknown event handler property `onKeyboardFocus`. It will be ignored. in div (created by IconMenu) in div (created by IconMenu) in IconMenu (created by DropdownMenu) in div ...

Need help with creating a unit test for the Material UI slider component? An error message saying "Error: Cannot read property 'addEventListener' of null" is displayed when trying to render the component

Encountered a problem while testing the Material-UI Slider with React-Test-Renderer: Uncaught [TypeError: Cannot read property 'addEventListener' of null] Codesandbox Link import React from "react"; import { Slider } from "@materi ...

Tips for incorporating confidence intervals into a line graph using (React) ApexCharts

How can I utilize React-ApexCharts to produce a mean line with a shaded region to visually represent the uncertainty of an estimate, such as quantiles or confidence intervals? I am looking to achieve a result similar to: ...

How can I establish default values for 2 to 3 options in a Dropdownlist?

Is there a way to set two values as default in a dropdown list, and when the page is refreshed, the last two selected values are retained as defaults? Thanks in advance! Visit this link for more information ...

The 'ngModel' property cannot be bound to a 'textarea' element because it is not recognized as a valid property

When I run Karma with Jasmine tests, I encounter the following error message: The issue is that 'ngModel' cannot be bound since it is not recognized as a property of 'textarea'. Even though I have imported FormsModule into my app.modu ...

Learn how to resubscribe and reconnect to a WebSocket using TypeScript

In my Ionic3 app, there is a specific view where I connect to a websocket observable/observer service upon entering the view: subscribtion: Subscription; ionViewDidEnter() { this.subscribtion = this.socket.message.subscribe(msg => { let confi ...

Aligning the React Navigation header component's bottom shadow/border width with the bottom tabs border-top width

Currently, I am working on achieving a uniform width for the top border of the React Navigation bottom tabs to match that of the top header. Despite my efforts, I am unable to achieve the exact width and I am uncertain whether it is due to the width or sha ...

In JavaScript, the function will return a different object if the string in an array matches the

My task involves working with a simple array of string ids and objects. Upon initial load, I am matching these Ids with the objects and setting the checked property to true. const Ids = ['743156', '743157'] [ { "id&quo ...

What is causing the malfunction in this overloaded function signature?

Encountering an issue when attempting to declare an overloading function type with a full type signature in TypeScript. For example: // Full type signatures for functions type CreateElement = { (tag : 'a') : HTMLAnchorElement, (tag ...

`Is there a way to maintain my AWS Amplify login credentials while executing Cypress tests?`

At the moment, I am using a beforeEach() function to log Cypress in before each test. However, this setup is causing some delays. Is there a way for me to keep the user logged in between tests? My main objective is to navigate through all the pages as the ...

Improving a lengthy TypeScript function through refactoring

Currently, I have this function that I am refactoring with the goal of making it more concise. For instance, by using a generic function. setSelectedSearchOptions(optionLabel: string) { //this.filterSection.reset(); this.selectedOption = optionLa ...

Learn how to display data from the console onto an HTML page using Angular 2

I am working on a page with 2 tabs. One tab is for displaying active messages and the other one is for closed messages. If the data active value is true, the active messages section in HTML should be populated accordingly. If the data active is false, th ...

What is the best way to insert a chart into a div using *ngIf in Angular?

I just started using chart.js and successfully created the desired chart. However, when attempting to implement two tab buttons - one for displaying tables and the other for showing the chart - using *ngIf command, I encountered an error: Chart.js:9369 F ...

What are the steps to incorporating the pick function in TypeScript?

The TypeScript documentation mentions a pick function that is declared but not implemented. In an attempt to create a simplified version, I wrote the following: function pick<T, K extends keyof T>(obj: T, key: K): Pick<T, K> { return { [key]: ...

Identifying misspelled names in shared resources textures during PIXI.js loading

Our game utilizes TypeScript, Pixi.js, VSCode, and ESLint. We maintain a dictionary of image files as follows: export function getAllImages(): {name: string, extension: string}[] { return [ {name: 'tile_lumber', extension: '.svg ...

The property 1 cannot be added because the object is not extendable in React

Does anyone know what is causing the following issue? I am unable to insert a new object into a key object within my arrays of objects. For example, when I try to insert a new email at index 1 in the 'emails' array, it throws an error stating "ca ...

NestJS Bull queues - Failing to secure job completion with a lock

I am currently utilizing Bull in combination with NestJS to manage a jobs queue. Within the process handler, I aim to designate a job as failed instead of completed. However, it appears - after carefully reviewing the documentation as well - that the Job#m ...

Encountered an issue while attempting to authenticate CMS signature using pkijs

I am attempting to validate a CMS signature generated with open ssl using the following command: $ openssl cms -sign -signer domain.pem -inkey domain.key -binary -in README.md -outform der -out signature Below is my code utilizing pkijs: import * as pkij ...

Tips for updating TypeScript aliases during compilation

To define a typescript alias in tsconfig.json, you can use the following syntax: "paths": { "@net/*":["net/*"], "@auth/*":["auth/*"], }, After defining the alias, you can then use it in you ...