I want to implement a recursive serial call to the promise method times
, returning the result of the fn
function of calling N times to the array.
At present, I added an additional attribute results
to the times
function to save the results of each fn
call.
I also don’t want to use module-scoped variables to save the results. Or, save the results by passing additional parameters like times(fn, n, results)
, it will break the function signature.
async/await
syntax is not allowed.
Is there any way to only use function local variables to save the result?
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' ]
}