Bird
0
0

What is the bug in this JavaScript async retry function for fetching data?

medium📝 Debug Q6 of 15
Rest API - Webhooks and Events

What is the bug in this JavaScript async retry function for fetching data?

async function fetchData() {
  let tries = 0;
  while (tries < 3) {
    try {
      const response = await fetch('https://api.example.com');
      if (response.ok) return 'Success';
    } catch (error) {
      // error handling
    }
  }
}
AThe response.ok check is incorrect; should check status 500
BThe function does not await the fetch call
CThe tries counter is never incremented, causing an infinite loop
DThe catch block immediately returns success
Step-by-Step Solution
Solution:
  1. Step 1: Analyze loop condition

    The while loop runs while tries < 3.
  2. Step 2: Check tries increment

    Inside the loop, tries is never incremented, so condition never changes.
  3. Step 3: Resulting issue

    This causes an infinite loop if response.ok is never true.
  4. Final Answer:

    The tries counter is never incremented, causing an infinite loop correctly identifies the bug.
  5. Quick Check:

    Increment loop counter to avoid infinite loop [OK]
Quick Trick: Always increment retry counter inside loop [OK]
Common Mistakes:
MISTAKES
  • Forgetting to increment retry attempts
  • Misusing response.ok property
  • Returning success inside catch block

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Rest API Quizzes