← JavaScript Coding

86. API Retry

medium
Asked at
Atlassian
Atlassian

Problem statement

Implement an asynchronous function retryApiCall that attempts to call a given API function and retries a specified number of times if the call fails or does not return a successful response (status code 200). The function should wait for a given interval between retries.

The function should accept the following parameters:

  • apiFunction: A function that makes the API call and returns a promise.
  • maxRetries: The maximum number of retries allowed.
  • retryInterval: The interval (in milliseconds) to wait between retries.

Function Signature:

async function retryApiCall(apiFunction: () => Promise, maxRetries: number, retryInterval: number): Promise

Example Usage:

const fetchData = async () => {
    // Simulated API call
    return fetch('https://example.com/data');
};

retryApiCall(fetchData, 3, 1000)
    .then(response => console.log('Data:', response))
    .catch(error => console.error('Failed to fetch data:', error));

Ensure that the function correctly handles retries, waiting the specified interval between attempts, and throws an error if the maximum number of retries is reached without a successful response.

How to approach 86. API Retry

The strategy an interviewer expects you to reach for.

API retry wraps a flaky network call: try again a few times before surfacing failure. Naive move Show an error on the first non-200, or retry forever without delay. Where it breaks Tight retries amplify outages. Success should return immediately. Exhausted attempts must return/throw the last failure clearly. The fix Loop up to maxRetries. await the API. On success (e.g. status 200), return. Else await a delay and continue. After the budget, return the last response or throw per the prompt. Remember: Finite retries + delay. First success returns; do not infinite-loop. Say this in the interview: I'd retry the API in a bounded loop with a delay between failures and return as soon as I get a successful response.

Premium

The full solution is part of HelloFrontend Pro

The question above is free to read in full. Upgrade to unlock the interactive workspace and the senior-level walkthrough that go with it.

  • Runnable editor with the hidden test suite
  • Progressive hints that unlock as you get stuck
  • Senior-level reference solution with a line-by-line walkthrough
Unlock the full solution →

Already a member? Log in to open the workspace.

More JS Coding questions

View all JS Coding →
JS CodingMedium

5. Throttle

JS CodingMedium

13. Deep Clone

JS CodingMedium

14. Event Emitter

JS CodingEasy

66. Promise Methods

JS CodingEasy

19. Memoize I

JS CodingEasy

mul(a)(b)(c)

Explore related prep hubs

  • All JavaScript coding
  • JavaScript interview questions
  • JS polyfill interview questions
  • Debounce & throttle questions
  • React interview hub
  • Atlassian interview