DEV Community

Dharan Ganesan
Dharan Ganesan

Posted on

Day 19: Retry

Question

Write a function retryAsyncOperation that takes an asynchronous operation represented as a Promise and retries it a certain number of times before rejecting the Promise.

function retryAsyncOperation(asyncFunction, retries, delay) {
    // Your code here
}

// Example usage
function simulateAsyncOperation() {
    return new Promise((resolve, reject) => {
        const success = Math.random() < 0.5; // Simulating success half of the time
        setTimeout(() => {
            if (success) {
                resolve("Success");
            } else {
                reject("Error");
            }
        }, 1000);
    });
}

retryAsyncOperation(simulateAsyncOperation, 3, 1000)
    .then(result => console.log("Result:", result))
    .catch(error => console.error("All attempts failed:", error));
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
dhrn profile image
Dharan Ganesan
function retryAsyncOperation(asyncFunction, retries, delay) {
    return new Promise((resolve, reject) => {
        function attemptOperation(attemptsLeft) {
            asyncFunction()
                .then(resolve)
                .catch(error => {
                    if (attemptsLeft > 0) {
                        setTimeout(() => attemptOperation(attemptsLeft - 1), delay);
                    } else {
                        reject(error);
                    }
                });
        }

        attemptOperation(retries);
    });
}
Enter fullscreen mode Exit fullscreen mode


`