Develop a custom function in Typescript that resolves and returns the values from multiple other functions

Is there a simple solution to my dilemma? I'm attempting to develop a function that gathers the outcomes of multiple functions into an array. TypeScript seems to be raising objections. How can I correctly modify this function?

const func = (x:number, y:number) => {x,y}

const compileFunctionValues = (num: number, func: () => unknown) => {

    const returnValues: Array<(unknown)> = []

    for (let i = 0; i < num; i++) {
        returnValues.push(func())
    }

    return returnValues
}

Error Encountered:

var result = func();
                     ^

TypeError: func is not a function
    at executeRepetitiveFunction

Answer №1

To retrieve a value from the function being passed and save it in an array, you can simply invoke the function and declare func as a specific type of Function. You can implement something along these lines:

const executeRepeatedFunction = (num: number, func: Function) => {

  const resultsArray: Array<(unknown)> = []

  for (let i = 0; i < num; i++) {
      resultsArray.push(func())
  }

  return resultsArray
}

const sampleFunc: Function = (): String => {
    return 'yes';
}

executeRepeatedFunction(3, sampleFunc); 

This code snippet will output yes three times and store it in an array. // Output: ['yes', 'yes', 'yes']

Answer №2

It has been pointed out that your code lacks coherence. The error message you are encountering is accurate - there is no function defined named func. While you have used func as a parameter in the declaration of your executeRepetitiveFunction function, it is only accessible within the scope of that function.

Therefore, the error is not relevant to the actual question you are posing, so let's focus on answering the intended question.

const executeRepetitiveFunction = (num: number, func: () => unknown) : Promise<Array<any>> => {

    return new Promise((resolve, reject) => {
        const returnValues: Array<any> = []
    
        for (let i = 0; i < num; i++) {
            returnValues.push(func())
        }
    
        resolve(returnValues);
    });
}

const valuesPromise = executeRepetitiveFunction(5, () => {
    return "Execution complete"
});

What is happening here? We start by defining our function executeRepetitiveFunction, which takes in a number and a function returning an unknown data type. This function returns a promise, resolving when the loop finishes.

We then proceed to execute this function immediately after declaration, providing it with the number 5 and an anonymous function that simply returns a value.

Once the execution is done, we can access our values by using

valuePromise.then(valuesArray => {console.log(valuesArray});
or handling them based on your requirements.

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

JavaScript's Array.map function failing to return a value

Here is a snippet of code from an api endpoint in nextJS that retrieves the corresponding authors for a given array of posts. Each post in the array contains an "authorId" key. The initial approach did not yield the expected results: const users = posts.ma ...

What is the best way to secure the installation of python packages for long-term use while executing my code within a python shell on NodeJS?

I have been encountering difficulties while attempting to install modules such as cv2 and numpy. Although I have come across a few solutions, each time the shell is used the installation process occurs again, resulting in increased response times. Below i ...

Combining CSR and SSR in the next iteration of our project will

In my application, I have three main user roles: Consumer, Merchant, and Admin. I want the pages that Consumers access to be SEO friendly and server rendered. However, for Merchants and Admins, I prefer them to be client rendered with their own respective ...

Navigating through an array in Pug

I'm currently extracting data from an external API in JSON format and sending it to my view. The main issue I'm facing is that one of the properties within the Object consists of an Array of Objects. Using the Pug Documentation for iteration, I&a ...

Awaiting Node.js/Mongoose to patiently loop through asynchronous tasks

I have a question that might be quite basic for some. I am working with an array in my mongodb database and need to query/find multiple elements from it. My goal is to set an error variable to true if at least one element passes an if-statement. However, ...

Apply styles specifically to elements that contain a child element

I have a scenario where there are multiple <p> elements with the same class names, but only one of them has a child element. My objective is to highlight only the <p> that contains a child, however, my current code ends up highlighting all of t ...

Transmitting a jQuery array from the client to the server using AJAX in

I've looked at so many posts about this issue, but I still can't get my code to work. My goal is to retrieve a PHP array of values from the checkboxes that are checked. Here is my code snippet: <!doctype html> <html> <head> & ...

Animate the leftward disappearance of a div to make it vanish

My goal is to create a user interface where users can navigate through different divs. Here is the HTML code: <article id="realize" class="realizeBox"> <div class="shown"> <div class="heading"> <h2>Realisati ...

Choose images at random from an array within a React Native application

I've been working on a feature that involves randomly selecting an image from an array of images. However, I keep running into the issue of getting an "invalid props source supplied to image" error. My goal is to display a different random image each ...

Accessing the selected value from a dropdown list filled with data from a PHP array in HTML

My HTML and PHP code consists of a select dropdown that looks like this: <select name="category" id="_category" class="_cateogry" onchange="submitTheForm() > option value="">Please select</option> <?php foreach ($categories as $cont ...

Is there a way to identify when a fresh google instant page appears?

I am currently developing a browser extension that requires making a call when a new Google instant page is loaded and then modifying the results, similar to SEOQuake. One problem I encountered is that if a user pastes a link directly into the URL field a ...

Project Anagramatics

I'm struggling with getting the "isZero" function to properly identify whether a word is an anagram or not. When I check if "isZero" equals 1 in the main() function, it always returns "anagram". Conversely, setting it to 0 always returns "not anagram" ...

Error: karma cannot locate the templateUrl for Angular component

I'm encountering some issues while running tests on angular directives with karma. The problem arises when the directive comes from a templateUrl and is not being translated properly. Here's my karma.conf.js configuration: 'use strict&apos ...

Is it true that the react setState function does not function properly with stream data?

I'm currently utilizing PouchDB to synchronize my remote database with my local database. The following code is integrated within the componentDidMount lifecycle method: const that = this var localDB = new PouchDB('localdb') var remoteDB = ...

What are the best practices for managing data input effectively?

I am facing a challenge with input validation. I need to restrict the input to only accept strings of numbers ([0-9]) for the entity input field. If anything else is entered, I want to prevent it from overwriting the value and displaying incorrect input. I ...

Search for records in MySQL using Typeorm with the condition "column like %var%" to retrieve results containing the specified

Looking for a way to search in MySql using typeorm with the "column like" functionality. async findAll({ page, count, ...where }: CategorySelectFilter): Promise<Category[]> { return this.categoryRepository.find({ where, ...

Is it possible to set data using a React Hooks' setter before the component is rendered?

Instead of making a real API call, I am exporting a JS object named Products to this file to use as mock data during the development and testing phase. My goal is to assign the state of the function to this object, but modified with mapping. The current st ...

Unable to launch React Native project on emulator now

Something seems off with my App as it won't start up on my AS Emulator. Everything was running smoothly yesterday, but today it's not working - possibly due to me moving the npm and npm-cache folders, although they are configured correctly with n ...

Utilize style as a module in Angular

The issue at hand: Let's take a look at this project structure: /src /public /styles /general /tables.scss /secure /components /someTable1 /someTable.component.ts /someTable.component.css /someTa ...

What is the process for creating a map in which the value type is determined by the key type?

Is it feasible to formulate a Map<K, V> in a manner where the type of the value relies on the type of the key, without explicitly specifying the key's type upon initializing the map? For instance: abstract class BaseA { a() {} } class ConcreteA1 ...