Write retry(task, attempts, cb) that runs an error-first async task, retries it on failure up to attempts times, and reports the final result or error. Test it with a task that fails twice and then succeeds.
function retry(task, attempts, cb) {
task((err, result) => {
if (!err) return cb(null, result);
if (attempts <= 1) return cb(err);
console.log(` failed (${err.message}), retrying…`);
retry(task, attempts - 1, cb);
});
}
let calls = 0;
const flakyUpload = (cb) => setTimeout(() => (++calls < 3 ? cb(new Error(`attempt ${calls}`)) : cb(null, `uploaded on attempt ${calls}`)), 0);
retry(flakyUpload, 5, (err, msg) => console.log(err ? `gave up: ${err.message}` : msg));
failed (attempt 1), retrying… failed (attempt 2), retrying… uploaded on attempt 3
Each failure schedules a new attempt by calling retry recursively with one fewer attempt left. The final callback is called exactly once – either with the success or with the last error.