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.