2

I have this Ajax request function.

export async function fetchAllCoinsPromise() {
  const apiCall = await fetch('https://api.coincap.io/v2/assets');
  const jsonResult = await apiCall.json();

  return jsonResult;
}

I call it like this:

  const fetchCoins = () => {
fetchAllCoinsPromise()
  .then(res => console.log(111))
  .catch(err => {
    console.log('err', err);
    fetchCoins();
  });
 };

the reason why I'am doing this recursion is because sometimes I'm getting this strange error: SyntaxError: JSON Parse error: Unexpected identifier "You"] and I thought the async recursion would solve the issue and it does but I am not sure if this is the best solution in case of time complexity. Any suggestions please?

16
  • 1
    What is the content of the response that fails to parse? Commented Oct 5, 2021 at 15:23
  • 1
    It sounds like that is the response you are expecting but not necessarily the response you are getting when it fails. The JSON parser is failing because it is not an array of objects. There could be a missing comma or it could be sending back an error message like "You need to authenticate before requesting this resource". Take a look and post the response that causes the actual error. Commented Oct 5, 2021 at 15:26
  • 2
    "You exceeded your 200 request(s) rate limit of your FREE plan" TADA>...... not JSON. Commented Oct 5, 2021 at 15:26
  • 1
    They have a rate limit.... you hit it somehow. Commented Oct 5, 2021 at 15:28
  • 1
    @user14587589 To handle these errors, Please check the Response Status Code before phrase the JSON Commented Oct 5, 2021 at 15:28

1 Answer 1

4

You can use a filter if you want. It might be a hacky solution but it works.

An example might look like:


if(jsonResult.startsWith('Y')){
  console.log("Error: " + jsonResult);
  tryYourCallAgain();
  } else {
  return jsonResult;
  }

You could use any filter that would catch the error like typeof, includes, etc. Whatever is best in your case.

Pardon if this code is sloppy as I'm relatively new to Javascript, but this worked for me in a similar case. Hope it helps!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.