JavaScript Interview Question #194

How would you implement a simple retry mechanism for an asynchronous operation?

Advanced JavaScript, Practical Problems & Senior Interview Scenarios Senior Advanced

Quick Interview Answer

A retry mechanism attempts an operation again after a failure, usually with a maximum number of attempts and often with a delay or backoff strategy. Retries should be limited to failures that are reasonably transient.

Detailed Explanation

A retry mechanism attempts an operation again after a failure, usually with a maximum number of attempts and often with a delay or backoff strategy. Retries should be limited to failures that are reasonably transient.

Do not automatically retry every operation. Non-idempotent requests, validation failures, authentication errors, and permanent server failures may require different handling. Production systems often use exponential backoff and cancellation.

Code Example

async function retry(operation, attempts = 3) {
    let lastError;

    for (let i = 0; i < attempts; i++) {
        try {
            return await operation();
        } catch (error) {
            lastError = error;

            if (i < attempts - 1) {
                await new Promise(resolve =>
                    setTimeout(resolve, 500)
                );
            }
        }
    }

    throw lastError;
}

const data = await retry(() =>
    fetch("/api/data").then(response => {
        if (!response.ok) {
            throw new Error(
                `HTTP ${response.status}`
            );
        }
        return response.json();
    })
);