Retry repeats a failed asynchronous operation a bounded number of times, optionally pausing between attempts. It helps tolerate intermittent failures in external services that the application cannot control. section 11.4.6
Listing 11.4 Implementation of a retry function in JavaScript
async function sleep(timeMS) { #1
return new Promise((resolve, reject) => { #2
setTimeout( #3
() => { resolve(); }, #4
timeMS #5
);
}); #2
}
async function retry(operation, maxAttempts, waitTimeMS) { #6
while (maxAttempts-- > 0) { #7
try {
const result = await operation(); #8
return result; #9
}
catch (err) { #10
lastError = err; #11
if (maxAttempts >= 1) {
await sleep(waitTimeMS); #12
}
}
}
throw lastError; #13
}
A JavaScript implementation wraps an asynchronous operation, returns immediately on success, records failures, and waits before another permitted attempt. section 11.4.6
Use retry with a deliberate failure-handling sequence:
- Limit attempts with a maximum count rather than retrying indefinitely. section 11.4.6
- Pause between attempts so an intermittent failure has time to clear. section 11.4.6
- Return the successful result; after the final failure, preserve the error for handling by the caller. section 11.4.6
Retrying an HTTP request
await retry(() => axios.get("https://something/something"), 3, 5); retries an Axios request up to three times with a five-millisecond pause between attempts. section 11.4.6
Retries complement timeouts: timeouts stop requests that hang, while retries give failed requests another opportunity to succeed. Automatic retries are one part of broader microservice fault tolerance. section 11.4.6 section 11.6




















