How to retry a failed promise in Javascript?
The problem: When a promise fails, we want to handle it by retrying it's request. We solve it by using recursion. We need to implement 2 functions. The first would be the delay function, the other would be the promise function Delay function: function wait ( t ) { return new Promise (( resolve ) => setTimeout ( resolve , t * 1000 )); } Promise function const promise = ( tries , delay ) => { function onError ( err ) { tried = tries - 1 ; if ( ! tried ) { throw err ; } return wait ( t ). then (() => promise ( tries , delay )); } return promise . catch ( onError ); }; Get the result by simply calling like this: promise ( 5 , 5 ). then ( result => console . log ( result ))