Skip to content
Advertisement

How to retry an async function with a delay in javascript?

I am trying to fetch a record from a database. Due to race conditions it is possible and even likely that the record isn’t there when I first try to fetch it. How do I wrap this in a retry logic without going mad? I seem to be too stupid for it

JavaScript

This code should retry n times with a delay of t milliseconds. Thanks and much love.

What I’ve tried:

JavaScript

The thrown error:

JavaScript

Advertisement

Answer

That promise.reject()/promise.resolve() approach is not going to work, you cannot resolve a promise from the outside. And you shouldn’t need to – just return/throw from your async function! The only place where you need to construct a new Promise is in a little helper function

JavaScript

Then you can write your function in a recursive manner:

JavaScript

or even in an iterative manner:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement