waiting for variables to be defined?

First way is setInterval::

var breakout_result = null;
var vendor_result = null;

function callback_breakout(error, response, body) {
    if (!error && response.statusCode == 200) {
        // console.log(body);
        var data = JSON.parse(body)
        breakout_result = data.result
        console.log(breakout_result)
    }
}

function callback_vendor(error, response, body) {
    if (!error && response.statusCode == 200) {
        // console.log(body);
        var data = JSON.parse(body)
        vendor_result = data.result
        console.log(vendor_result)
    }
}

request(options_breakout, callback_breakout);
request(options_vendor, callback_vendor);


var interval = setInterval(function() {
   if ( breakout_result !== null && vendor_result !== null ) {
       clearInterval(interval);
        
       res.render('report',{
          breakout_result,
          vendor_result
       });
   }
}, 500);

Second way is use callback::

var breakout_result = null;
var vendor_result = null;

function callback_breakout(error, response, body) {
    if (!error && response.statusCode == 200) {
        // console.log(body);
        var data = JSON.parse(body)
        breakout_result = data.result
        console.log(breakout_result)
    }
}

function callback_vendor(error, response, body) {
    if (!error && response.statusCode == 200) {
        // console.log(body);
        var data = JSON.parse(body)
        vendor_result = data.result
        console.log(vendor_result)
    }
}

// init request1
request(options_breakout, function() {
   callback_breakout(); // process request1

   // init request2
   request(options_vendor, function() {
        callback_vendor(); // process request2

        // now render content
        res.render('report',{
          breakout_result,
          vendor_result
       });
   });
});

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top