I have a wrapper function that calls an async function:
function fetchAPI(arg1: number, arg2: number, arg3: string) {
return new Promise((resolve, reject) => {
try {
myFetchFunction(arg1, arg2, arg3).then((r: any) => {
if (!r) {
reject("Error 01")
}
resolve(r)
})
} catch {
reject("Error 01")
}
})
}
Due to the instability of the API being queried, the fetchAPI
function frequently rejects.
To address this issue, I created another function that iterates over the fetchAPI
function up to 3 times (with a 1-second wait interval between attempts). If all attempts fail, it resolves with undefined
. If any attempt succeeds, it simply resolves with the correct response.
function fetchAPIRepeat(arg1: number, arg2: number, arg3: string, n: number = 0) {
return new Promise((resolve) => {
fetchAPI(arg1, arg2, arg3).then((r) => {
resolve(r)
}).catch(() => {
if(n < 3) {
console.log("Partial error: " + n)
sleep(1000).then(() => {
resolve(fetchAPIRepeat(arg1, arg2, arg3, n + 1))
})
} else {
resolve(undefined)
}
})
})
}
This solution works well for me. However, I would like to create a more generic wrapper that functions similarly to the fetchAPIRepeat
but can be used with any promise-based function.
Although I attempted to create such a 'general wrapper', it is not functioning as expected:
function promiseRepeatWrapper(fn: (...args: any[]) => Promise<any>, n: number = 0, ...args: any[]) {
return new Promise((resolve) => {
fn(args).then((r) => {
resolve(r)
}).catch(() => {
if(n < 3) {
console.log("Partial error: " + n)
sleep(1000).then(() => {
resolve(this.errorWrapper(fn, n + 1, args))
})
} else {
resolve(undefined)
}
})
})
}
The current issue is that the console logs 'Partial error' three times and then resolves with undefined, even when the promise successfully completes all three attempts:
Partial error: 0
Partial error: 1
Partial error: 2
In addition to fixing the functionality of the function, I am open to suggestions on improving the error-handling design for my promise-repeat pattern.
Thank you.