Error message: An uncaught promise was encountered, despite adding a catch function. I am unable to identify the issue causing this error

Why is the added catch block not functioning properly?

function maxRequest(url = ``, times = 3) {
  // closure
  function autoRetry (url, times) {
    console.log('times = ', times);
    times--;
    return new Promise((resolve, reject) => {
      fetch(url).then(value => {
        if(value.status === 200) {
          console.log(`✅ `, value);
          resolve(value);
        } else {
          throw new Error(`❌  http code error: ${value.status }`);
        }
      }).catch((err) => {
        console.log(`❌  Error`, err);
        if (times < 1) {
          reject('💩  over max request times!');
        } else {
          autoRetry(url, times);
        }
      });
    });
  }
  return autoRetry(url, times);
}

maxRequest(`https://cdn.xgqfrms.xyz/json/badges.js`)
  .then(res => res.json())
  .then(json => {
      console.log('json =', json);
      return json;
  }, err => {
      console.log('error =', err);
      throw new Error(err);
  })
  .catch(err => console.log(`err =`, err))
  .finally(() => {
      console.log('whatever close loading...');
  });

https://i.sstatic.net/2KjMo.png

https://i.sstatic.net/uSWIa.png

Answer №1

Your approach to handling the explicit Promise construction antipattern may be leading to uncaught rejected Promises due to a missing return statement in your catch block. When attempting a retry, the newly created Promise using autoRetry is not being utilized effectively, leaving vulnerabilities in error handling within the call to maxRequest.

function maxRequest(url = ``, attempts = 3) {
  // closure function for retry logic
  function autoRetry(url, attempts) {
    console.log('attempts = ', attempts);
    attempts--;
    // Implementing fetch with chained promises
    return fetch(url).then(data => {
      if(data.status === 200) {
        console.log(`✅ `, data);
        return data;
      } else {
        throw new Error(`❌  HTTP code error: ${data.status}`);
      }
    }).catch((error) => {
      console.log(`❌  Error`, error);
      if (attempts < 1) {
        throw new Error('💩  Exceeded maximum request attempts!');
      } else {
        return autoRetry(url, attempts);
      }
    });
  }
  return autoRetry(url, attempts);
}

maxRequest(`https://cdn.xgqfrms.xyz/json/badges.js`)
  .then(response => response.json())
  .then(jsonData => {
      console.log('jsonData =', jsonData);
      return jsonData;
  }, error => {
      console.log('error =', error);
      throw new Error(error);
  })
  .catch(error => console.log(`error =`, error))
  .finally(() => {
      console.log('Closing loading process...');
  });

Consider improving clarity by updating variable names and simplifying the implementation as an async function with a looping structure.

https://i.sstatic.net/zCINx.png

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

`The challenge of a single web page not displaying correctly`

I was working on a website for a local computer building company, and I decided to make it a single-page applet. The HTML is mostly done, and I don't have much trouble with CSS. However, I encountered an issue with hiding and displaying different sect ...

What is the method for asynchronously loading a javascript file that includes an ajax call?

Within my JavaScript file named JScript.js, there is a function that includes an AJAX call to a dot-net page. alert('jscript.js called'); function AddTag() { var htag = document.getElementById("hdntag").value.split('|'); var texttag = ...

Using JavaScript to implement word filtering in MongoDB

I'm currently in the process of creating a chatbot designed to filter questions, and I'm seeking guidance on how to refine the search in my MongoDb based on user input. At the moment, I have the following code: I aim to retrieve all the results ...

Tally up various figures in all tables

I am dealing with a dynamic table generated from a PHP loop. Below is an example of the table structure extracted from the browser source code: <table class="table"> ... (table content) </table> <table class="table"> ... (t ...

Troubleshooting unexpected behavior with Custom Guest middleware in Nuxt Project

I have implemented the Nuxt auth module for my project. To manage the login page, I created a custom middleware called guest.js, which has the following code: export default function ({ $auth, store, redirect }) { if (!process.server) { if ($auth ...

The Daterangepicker function moment() outputs numerical values

Within my .cshtml file, I have integrated a daterangepicker.js script. This page retrieves the date range (from date, to date) from a parent page using ViewBag. The code snippet is as follows: var _FromDate; var _EndDate; $(function () { var from1 = ...

Struggling to get a package running in Next.js that is functioning perfectly in ReactJS

Link I have integrated the JSME React npm package into my application to utilize the JSME editor. While this package works seamlessly in a ReactJS environment, I am encountering issues when trying to use it in a Next.js project. I am receiving an error mes ...

Having trouble importing Bootstrap into Next.js? It seems like the issue may be related to the

I am currently facing an issue with importing bootstrap 5.3.2 (not react-bootstrap) into my NextJS 14.1.0 project that utilizes the new App Router. My goal is to strategically utilize individual Bootstrap components (not through data-attrs). I managed to ...

Trouble with JavaScript confirm's OK button functionality in Internet Explorer 11

Having trouble with the OK button functionality on a JavaScript confirm popup in IE11. For one user, clicking OK doesn't work - nothing happens. It works for most other users though. Normally, clicking OK should close the popup and trigger the event h ...

Locate a specific sequence of characters within an array of objects using JavaScript

I am working with an array of objects, where each object contains a string value. My task is to search for a specific substring within the string. [ { "link": "https://www.sec.gov/Archives/edgar/data/1702510/000170251022000084/00 ...

Is it possible to utilize AJAX to load the URL and then extract and analyze the data rather than

I had originally created a web scraping method using PHP, but then discovered that the platform I was developing on (iOS via phone gap) did not support PHP. Fortunately, I was able to find a solution using JS. $(document).ready(function(){ var container ...

Error while retrieving reference from mongoDB in NodeJS

I am currently working on a small website that needs to query my local mongodb. Everything works perfectly fine on localhost. That's why I decided to begin with NodeJS. While all JavaScript functions work seamlessly when run separately, I encounter a ...

Stop automatic form submissions from the enter key

My live chat messaging system is experiencing an issue where the page refreshes every time a user presses the enter button. I attempted to use prevent default code, but it did not work for me. I'm new to website programming, so if there are any proble ...

What are some other options for pushing out data instead of using window.onbeforeunload?

I have an AJAX function that interacts with my PHP script. The purpose was to delete empty MySQL entries when the user closes the page. Initially, I thought window.onbeforeunload would be ideal for this task, but it seems in the latest version of Chrome i ...

Having trouble signing out in Nextjs?

As a newcomer to Reactjs and Nextjs, I am currently working on developing an admin panel. To handle the login functionality, I have implemented the following code in my index.js/login page using session storage: const data = { name: email, password: pa ...

Prevent caching of JavaScript variables in EJS mode

Is there a way to turn off ejs cache? I came across a solution: ejs.clearCache() However, this method requires an instance of ejs to work. Currently, I am only using: app.set('view engine', 'ejs'); Therefore, I am unsure how to cle ...

Switch between a list of labels dynamically with checkboxes in React

I'm currently working on a React component that displays an array of cars. I want to show a list of labels with the names of all diesel cars by default, and then have a checkbox that, when clicked, toggles to show all cars. interface ICars { name ...

Retrieve the script's location from the server prior to the initialization of Angular

Is there a way to dynamically add a script in the index.html page based on the application version? I have a controller that retrieves the app version and attempted to achieve this using AngularJS: var resourceLoader = angular.module('MyTabs&apo ...

Click the mouse to create a unique path from the list items within the <ul> <li> using jQuery

My current listing contains various files and folders: <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fon ...

What is the best way to handle a specific submit button using jQuery/Ajax?

I created a web page with 4 submit buttons that all call the same PHP page process.php using jQuery/Ajax. I trigger this PHP page using the onClick event as shown below: <div class="col-md-12"> <input type="hidden" name="_token" value="<?p ...