0

I am calling an api to monitor the state of the response. I have to keep calling api until the response state is successfull. I am calling

I am calling getHeader function from another js file to get the response from API get call. I have to keep calling api again and again until the result.success is successfull. However when the state is changed to successfull, the function stop and doesn't return resolve. I think everytime i call function a new promise is created and it is not able to return resolve.

Can someone help me on this.

*import Promise from 'bluebird'
var requestPromise = Promise.promisifyAll(require('request'))
var instance;
const MonitorResponse = class {
    constructor() {
        if (instance) {
            return instance;
        }
        instance = this;
       }
    /**
     * 
     */
    getHeader(authToken,statusHeader) {
      console.log(" Successeded Get Geader " + statusHeader + " " +authToken );

      return new Promise(function (resolve, reject) {
        var self=this;
        var options = {
          method: 'GET',
          rejectUnauthorized: false,
          strictSSL: false,
          url: statusHeader,
          headers: {
            'Authorization': 'Bearer ' + authToken,
          },
          json:true
        };

            requestPromise.getAsync(options)
            .then(function (headerResponse) {
                console.log("Response Get Header " + JSON.stringify(headerResponse));
                var state = headerResponse.body.state;
                console.log("Response Get Header state " +state );

                if(state=="SUCCESSFUL")
                {
                  return resolve(" from loop ");              
                }
                else{
                   self.getHeader(authToken,statusHeader);  
                  console.log(" After recursion state " +state );
                }

              })
              .catch(function (error) {

                return reject(error)
              });

        }.bind(this));
      }    

}   
module.exports = MonitorResponse*

Expected Result is to get return resolve(" from loop "); when getHeader function is called.

user2641452
  • 105
  • 2
  • 10
  • 1
    Avoid the [`Promise` constructor antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it)! – Bergi Oct 24 '19 at 21:43
  • i am able to fix the issue. I have created a nested function inside. Instead of calling getHeader function, i am calling the nested function which avoids creating a new promise every time and hence able to return the resolve object. Thanks – user2641452 Oct 25 '19 at 14:06

0 Answers0