1

Why can't I call resolve in the catch block ?

Wanted catch a failed request and try it again in the catch block but I'm getting resolve is not defined. I'm inside of the promise why cant I call resolve

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

return Promise()
  .then(function(val, 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 repead the request (attempts left: ${requestAttempts} )`); 
        resolve(makeRequest(ID,requestAttempts - 1)); //HERE
  });

}
Samy
  • 1,013
  • 3
  • 15
  • 25
  • No no no. You will want to read [How do I convert an existing callback API to promises?](https://stackoverflow.com/q/22519784/1048572) – Bergi Mar 05 '18 at 11:44

2 Answers2

2

The Promise constructor takes a function with resolve and reject. .then does not. If you want to resolve out of a .then or a .catch, just return the value. If you want to reject out of a .then or a .catch, just throw an error.

I think you want something like this - just follow the structure - the logic might not be what you want.

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 repead the request (attempts 
        left: ${requestAttempts} )`); 
    return makeRequest(ID,requestAttempts - 1));
 }); 
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
1

Your use of the Promise constructor is incorrect, and your resolve function is not within the scope of the .catch function's callback. Your makeRequest function is also not exposed in the local scope so it can't even call itself.

I would further suggest moving the "retry" logic outside of the core function that actually processes 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;
Alnitak
  • 334,560
  • 70
  • 407
  • 495