The identifier "resolve" in the catch block has not been defined

Why is it not possible to call resolve in the catch block?

I wanted to catch a failed request and attempt it again in the catch block, but I am encountering an issue where resolve is not defined. I am confused since I am inside of the promise, so why is it not allowing me to call resolve?

module.exports.makeRequest = function(ID, requestAttempts) {

return new Promise(function(resolve, reject) {
    request.get(url, {json:true}, function(err, res) {
        if(err || res.body.error_code)
            reject(err || res.body)
        else
            resolve(res.body)
    })
})
.catch(function(error) {
    if (requestAttempts <= 0) {
        reject(error);
    }
    console.log("Error:", error, `\n Try to repeat the request (attempts left: ${requestAttempts})`); 
    resolve(makeRequest(ID, requestAttempts - 1));
});

}

Answer â„–1

The Promise constructor requires a function with resolve and reject, while .then does not. To resolve from a .then or a .catch, simply return the value. To reject from a .then or a .catch, just throw an error.

If you're looking for a similar structure, consider the following example. Remember, the logic may need adjustment to suit your needs:

function makeRequest(ID, requestAttempts) {
   return Promise((resolve, reject) => {
       request.get(url, {json:true}, function(err, res) {
          if(err || res.body.error_code)
              reject(err || res.body)
          else
              resolve(res.body)
       })
    })
}

 makeRequest().catch(function (error) {
     if (requestAttempts <= 0) throw error;
        console.log("Error :",error, `\n Try to repeat the request (attempts 
        left: ${requestAttempts} )`); 
    return makeRequest(ID, requestAttempts - 1));
 }); 

Answer â„–2

Your implementation of the Promise constructor seems to have some errors. The resolve function is not properly placed within the .catch function's callback, leading to scope issues. Additionally, the makeRequest function is not accessible in the local scope, making it impossible to call itself.

I recommend moving the "retry" logic outside of the main function responsible for processing the AJAX request.

function makeOneRequest(ID) {
    return new Promise((resolve, reject) => {
         request.get(url, {json: true}, (err, res) => {
             if (err || res.body.error_code) {
                 reject(err || res.body);
             } else {
                 resolve(res.body);
             }
         });
    });
}

function makeRequest(ID, count) {
    if (count <= 0) {
        return Promise.reject();
    } else {
        return makeOneRequest(ID).catch(() => makeRequest(ID, count - 1);
    }
}

module.exports.makeRequest = makeRequest;

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

Calculating the dot product of two arrays using JavaScript

let array1 = [2,4,6] let array2 = [3,3,3] let result = dotProduct(array1,array2) // should return 36 Can you suggest a streamlined approach to creating the dotProduct function without relying on external libraries? ...

Is it feasible to indent lines in a template without affecting the content alignment?

Creating a string with newlines that will be included in an email later. if (action) { description = ` Git pull request action: ${action} Git pull request for repo: ${req.body.repository.full_name} Git pull request for repo URL: ${re ...

Tips for transferring JSON data to a CodeIgniter view

I have a query regarding how to replace a specific section of my webpage with data returned from the controller. Currently, I have a page that displays movie details directly fetched from the database. My goal is to only display movies of a particular genr ...

How can I efficiently retrieve the name variable of a Quasar (or Vue 3) application?

Is there a way to incorporate something similar in Quasar without having to redefine the variable in every component? <template> <div>Enjoy your time at {{ APP_NAME }}.</div> </template> During the setup of my app with Quasar C ...

Codeigniter dilemma: Unable to upload images using Summernote

Summernote has been successfully integrated into my website (which is built using Codeigniter). Text editing functions work perfectly fine, however, I'm facing an issue with image uploads. When uploading images, Summernote reads them as base64. This ...

Creating a multi-dimensional array in JavaScript with two different sizes

I'm struggling to find the best way to create a multi-dimensional array with varying sizes dynamically. Our user interface requires a pattern where there are rows of 4 items followed by rows of 3 items. This pattern should continue until all contents ...

Run the command "node index.js" to simultaneously start and stop the server

After installing WSL2 and the Ubuntu 22.04 distribution on Windows 11, I set up my environment, installed nvm, Node version 16.17.1, and then ran npm init in my folder. Following that, I installed Express and created an index.js file with a simple structur ...

How can I transfer an array of objects obtained from an ajax call to an observable array?

One of my functions involves making an ajax call and receiving data in the callback. It looks something like this: function fetchData(callback) { //perform ajax if(callback) { callback(data.data); } } If I use the function like this: fetc ...

Verify if the JSON attribute is empty

My input contains the following: { "headers": { ... }, "body": { "RequestInfo": { ... , "Identificator": null } } <filter regex="false" source="boolean($ctx:Identificator)"> - check if it exists (even when it's ...

Regular Expression - Locate all numerical values within text formatted with HTML

I am attempting to locate all the numbers within an HTML document. However, I want to ensure that I exclude numbers that are part of a word, such as "o365", "high5", and similar instances. Here is my current approach, but it does not successfully avoid w ...

Turning an Array of Objects into a typical JavaScript Object

Below are arrays of numbers: var stats = [ [0, 200,400], [100, 300,900],[220, 400,1000],[300, 500,1500],[400, 800,1700],[600, 1200,1800],[800, 1600,3000] ]; I am seeking guidance on how to transform it into the JavaScript object format shown below. ...

Can you please identify the TypeScript type associated with the return value of the match() method in String prototype?

I need help with creating a Regex in JavaScript const pattern = /S(\d+)E(\d+)/; // identifying characters between "S" and "D" const result = 'SE01E09'.match(pattern); How should I declare the result variable? I have attempted various ...

Determining a User's Connection Status in ReactJS: Cellular Network or WiFi?

Are there any tools or applications available that can determine if a user is connected to WiFi or using a cellular network? ...

What is the best way to compare dates in PostgreSQL timestamp with time zone?

In my PostgreSQL database, there is a field labeled as "timestamp with time zone compare" Currently, I am trying to implement a data range comparison using JavaScript var start = Date.UTC(2012,02,30);//1333065600000 var end = Date.UTC(2013,02,30); //136 ...

Filtering an array within an array based on user input

I am currently facing a challenge in filtering the child elements of an array. I am puzzled on how to specifically target children elements. So far, my filter is only functioning at the top level. Array: options: [ {name: 'Ð’Ñ‹Ñ…Ð ...

How come I am receiving the E11000 error from Mongo when I have not designated any field as unique?

Encountering an issue while attempting to save the second document to MongoDB Atlas. The error message reads as follows: Error:MongoError: E11000 duplicate key error collection: test.orders index: orderId_1 dup key: { orderId: null } Despite having no un ...

Changing selections in jQuery may not work properly on certain mobile and IE browsers

I am currently working on creating a dependency between two select boxes. The jQuery code I have implemented works perfectly on most common browsers such as Chrome and Firefox, but it seems to have some issues with Internet Explorer, Edge, and some mobile ...

Validation in AngularJS is limited to only accepting integers with the use of the

Can you help me with validating positive integer numbers using the ng-pattern attribute? Currently, I have this pattern: ^[0-9]{1,7}(\.[0-9]+)?$/, but it also allows decimal values. I want to restrict it to only accept whole numbers. ...

"What is the best way to access the value of a useState variable in ReactJS on a global

Below is my reactJS code snippet - useEffect(()=>{ const getinterviewerDetails= async ()=>{ const data1 = await axios.get("http://localhost:8083/api/GetProduct") .then(response => { console.log("role is " ...

What is the purpose of encasing the routes within the <Switch> element in react-router, when they seem to function perfectly fine without it

Currently utilizing react-router-dom version 5.2.0. As a practice, I typically enclose all my Route components within a Switch component. For instance: const MyRoutes = () => ( <Switch> <Route path='/route1' exact ...