Learn the art of generating multiple dynamic functions with return values and executing them concurrently

I am currently working on a project where I need to dynamically create multiple functions and run them in parallel.

My starting point is an array that contains several strings, each of which will be used as input for the functions. The number of functions matches the length of the array.

However, I have encountered an issue with my code and I'm unsure how to resolve it.

TS2345: Argument of type 'Promise' is not assignable to parameter of type '(data: string) => Promise'. Type 'Promise' does not match the signature '(data: string): Promise'.

I am seeking guidance on how to properly push the function into the list so that the return value can be stored in the data later on.

  private async runParallel() {
        let listOfFunctions: ((data: string) => Promise<string>)[] = [];
        let outline: string[] = ["test1", "test2", "test3"]

        for (let i = 0; i < outline.length; i++) {
            let func = async (input: string): Promise<string> => {
                // include async/await calls...
                return input;
            };
            listOfFunctions.push(func(outline[i])); // TS2345 error occurs here

        }
        const data = await Promise.all(listOfFunctions);

        console.log(data);
    }

Answer №1

Since the function is already being executed ->

func(outline[i])

You are not returning a function that gives a Promise of a string, you are simply adding a Promise for a string to the array.

The solution is to remove the function part from your array.

For example:

let listOfFunctions: (Promise<string>)[] = [];

In other words, the function aspect is handled before it is added to the array, but don't worry, it will still run in parallel.

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

Circular graphs displaying percentages at their center, illustrating the distribution of checked checkboxes across various categories

Looking for a JavaScript script that displays results in the form of circles with percentage values at their centers, based on the number of checkboxes checked in different categories. The circle radius should be determined by the percentage values - for e ...

What is the best way to eliminate the left margin entirely in CSS?

I am attempting to create an image view that fully covers the window, without any margins. I have tried various solutions such as setting the body margin and padding to 0, but they do not seem to work. body { margin: 0px; padding: 0px; } or *, html { ...

Using Node.js Express to showcase a JSON file utilizing Class Methods

Recently diving into node.js and express, I attempted to display a JSON file containing an array of 3 objects using a class method Below is the Class structure: const fs = require('fs') class GrupoArchivo { constructor(filePath) { t ...

What is the technique for arranging the display of a component in React?

Is there a way to dynamically render a component in my react-app at a specific date and time, like 6.00PM on October 27, 2022? I want to release a form for signing up starting from that exact moment. The timestamp information will be stored in my database ...

Using jQuery to enable scrolling and dynamically changing classes

I'm currently working on enhancing my website with a feature that changes the opacity of the first section to 0.4 when a user scrolls more than 400 pixels down the page. I attempted the following code without success: if($("html, body").offset().top ...

JavaScript - Not a Number

I am currently facing an issue while attempting to calculate the Markup of a product. I keep receiving a 'NaN' error in my console, which I understand stands for Not a Number. However, I am struggling to identify and rectify the root cause of thi ...

establishing the default value as p-multiselect

Here is the code snippet I am currently working on: export class LkBoardStatus { id : number = 0; descr : string = ''; } In the component.ts file, I have defined the following: //... lkBoardStatusList: LkBoardStatus[] = []; selectedStat ...

What is the method for retrieving the IDs of checkboxes that have been selected?

I attempted running the following code snippet: <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="text/javascript" src="http://static.jstree.com/v.1. ...

Is there a more efficient method for iterating through this object?

Working with JSON and JS var data = { "countries": { "europe" : [{name: "England", abbr: "en"}, {name: "Spain", abbr: "es"}], "americas" : [{name: "United States"}], "asia" : [{name: "China"}] } }; JavaScript Loop for (k in data) { fo ...

Utilizing Chart.js for generating a sleek and informative line graph

After executing a MySQL query, I obtained two tables named table1 (pl_pl) and table2 (act_act) with the following data: table1: label act_hrs Jan-19 7 Feb-20 8 Mar-20 9 table2: label pl_hrs Mar-20 45 Apr-20 53 I am looking to create a line cha ...

The random number generator often omits both the upper and lower limits

I am working with an array that contains letters from A to H. However, when using a random number generator, I have noticed that the letters A and H are rarely selected. How can I adjust my approach to make sure these two bounds are included more often? ...

Create efficient images using Node.js and express using sharp or canvas

Struggling with optimizing image rendering using node, express, and sharp. Successfully implemented an upload method with Jimp for images over 2000px wide and larger than 2mb in file size. While many libraries can achieve this, Jimp was more memory-effici ...

Tips for preventing the need to convert dates to strings when receiving an object from a web API

I am facing an issue with a class: export class TestClass { paymentDate: Date; } Whenever I retrieve an object of this class from a server API, the paymentDate field comes as a string instead of a Date object. This prevents me from calling the ...

Develop an application using ASP.NET MVC that allows for returning a JavascriptResult along with a

Imagine this situation When using MVC, it is quite simple to send a Javascript code back to the client for execution public ActionResult DoSomething() { return JavaScript("alert('Hello world!');"); } On the client side, ...

Having difficulty locating the login button on the webpage

I am attempting to log into a banking account using selenuim. After opening the webpage and locating the login element, I initially struggled to access it by its "name" or "id." Fortunately, I was able to successfully access it using driver.find_element_by ...

Adding an Icon to a Tab in Ant Design - A Step-by-Step Guide

Is there a way to include an icon before the title of each open tab? I am currently using the antd library for tab creation, which doesn't provide a direct option for adding icons. Here is my code snippet along with a link to the jsfiddle https://jsfi ...

Modifying HTML elements with JavaScript - a practical guide

I'm trying to dynamically add the variable x to an existing HTML tag. The goal is to update the image tag <img id="Img" src="IMG/.jpg"/> by appending the variable x at the end of its id and source: <script> var images ...

Acquire Superheroes in Journey of Champions from a REST endpoint using Angular 2

Upon completing the Angular 2 Tour of heroes tutorial, I found myself pondering how to "retrieve the heroes" using a REST API. If my API is hosted at http://localhost:7000/heroes and returns a JSON list of "mock-heroes", what steps must I take to ensure a ...

Ways to prevent my website from being accessed through the Uc Browser

Is there a way to prevent my website from functioning on UC Browser using HTML or JavaScript? ...

Is there a way for me to properly type the OAuthClient coming from googleapis?

Currently, I am developing a nodemailer app using Gmail OAuth2 in TypeScript. With the configuration options set to "noImplicitAny": true and "noImplicitReturns": true, I have to explicitly define return types. Here is a snippet of my code: import { goog ...