index.tsx269 chars16 lines
Here, we define a function retry
that takes another function func
as input. The retry
function returns a closure that can be called with arbitrary arguments, representing the arguments for func
. Within this closure, we try to execute func(...args)
and return its result if successful. If func
throws an error, we catch the error and check if we have already retried the function three times. If we have retried three times, we simply re-throw the error. If we have not retried three times, we increment the attempts
counter and recursively call the closure returned by retry(func)
with the same arguments (...args)
.
By using recursion and a closure, we are able to retry the func
function up to three times if it fails, without having to modify the original implementation of func
or having to replicate its argument list in the retry function.
gistlibby LogSnag