Home > OS >  create a function that resolves/returns the value of other functions Typescript
create a function that resolves/returns the value of other functions Typescript

Time:02-17

I know theres probably an easy answer to this but I'm trying to create a function that resolves / returns the value of a variable amount of functions into an array. However it looks like typescript doesn't like this. What would be the appropriate way to write / fix this function

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

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

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

    return returnValues
}

error

var result = func();
                     ^

TypeError: func is not a function
    at executeRepetitiveFunction

CodePudding user response:

If you want to return something from the function you are passing and store it in an array, you can just call it and declare func as a Function type. You can do something like this:

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

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

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

  return returnValues
}

const testFunction: Function = (): String => {
    return 'ok';
}

executeRepetitiveFunction(5, testFunction); 

This will return ok 5 times and store it in an array . // Output: ['ok', 'ok', 'ok', 'ok', 'ok']

CodePudding user response:

As someone said, your code doesn't make sense. The error you're seeing is completely accurate - you have no function defined called func. You have func set up as the name of a parameter in your executeRepetitiveFunction function declaration, but it's not available outside of that function's scope.

So that error is irrelevant to the question you're asking, and I'll just answer the question you're actually asking.

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"
});

So what happens here? First we declare our executeRepetitiveFunction function, which takes two parameters, a number and a function which returns an unknown data type. Then we return a promise from this function, which resolves once the loop is complete.

We execute the function after it's declared, by calling the executeRepetitiveFunction function and passing it a number (5) and an anonymous function that simply returns a value.

Then when that's done, we can access our values by calling valuePromise.then(valuesArray => {console.log(valuesArray}); or handling it however else you want.

  • Related