I am looking to create a recursive serial call to the promise method times
, which will return the result of calling the fn
function N times and storing the results in an array.
To achieve this, I have added a new attribute called results
to the times
function to store the output of each invocation of fn
.
I want to avoid using module-scoped variables or passing extra parameters like times(fn, n, results)
as it would alter the function signature.
Furthermore, I need to find a solution that restricts the use of async/await
syntax.
Is there a way to utilize only function-local variables to store the results?
const times = Object.assign(
(fn: (...args: any) => Promise<any>, n: number = 1) => {
if (n === 0) return times.results;
return fn().then((res) => {
times.results.push(res);
return times(fn, --n);
});
},
{ results: [] as any[] },
);
Usage:
const createPromise = (args: any) =>
new Promise((resolve) => {
setTimeout(() => {
console.log(`[${new Date().toISOString()}]args: `, args);
resolve(args);
}, 1000);
});
async function test() {
const actual = await times(() => asyncFn('data'), 3);
console.log(actual); // output: [ 'data', 'data', 'data' ]
}