I have this async block:
test().then(function(result){
// Success: Do something.
doSomething();
}).catch(function(error){
// Error: Handle the error, retry!
// How to re-run this whole block?
});
I can keep track of the success
and failed
outcomes. However, is it possible to retry the whole test().then().catch()
chain if we fail? And keep retrying until the condition resolves?
If you can switch to async/await
syntax, you can use a while
loop:
let keepTrying;
do {
try {
await test();
keepTrying = false;
} catch {
keepTrying = true;
}
} while (keepTrying)
doSomething();
You could then abstract the retrying logic into its own function to be reused.
Assuming it's all about resending request to some buggy/bloat-up 3rd party API
If it's production question rather educational one I'd suggest search for 3rd party lib that implementing this on your own.
Say for axios
there is nice axios-retry
.
Why? Assume you may think there is just one case when API say returns 502. But actually there are much more cases it'd be better to keep in mind:
Writing such a logic on your own would be real overkill. And trying to use simplest solution may hit you when you don't expect it.
PS also as a bonus you would be able to configure all requests to some specific API with single snippet like it goes for axios
' custom instances(and I believe there should other plugins for alternative libraries)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With