Here's an example snooze function (not tested yet):
function retry(maxRetries, fn) { return fn().catch(function(err) { if (maxRetries <= 0) { throw err; } return retry(maxRetries - 1, fn); }); }
The idea is that you can wrap a function that returns a promise with something that will catch and repeat the error until the retry ends. Therefore, if you are going to repeat sendResponseAsync :
receiveMessageAsync(params) .then(function(data)) { return [data, handleMessageAsync(request)]; }) .spread(function(data, response) { return [response, deleteMessageAsync(request)]; }) .spread(function(response, data) { return retry(3, function () { return sendResponseAsync(response); }); }) .then(function(data) { return waitForMessage(data); }) .catch (function(err) {
Since the promise of retry will not actually be thrown out until all attempts have been exhausted, your call chain may continue.
Edit
Of course, you can always loop forever if you want:
function retryForever(fn) { return fn().catch(function(err) { return retryForever(fn); }); }
Jacob source share