I am trying to access the variable which is declared globally and assigned inside a callback function. I want to access the value outside. Is there a way to do that ?
what I tried :
Node JS(onvif module).
var jsonObject ='[';
var count = 0;
var len = cams.length;
cams.forEach(function(cam) {
var hardwareId,serialNumber;
cam.getDeviceInformation(function(a,b,c){
hardwareId = b.hardwareId;
serialNumber = b.serialNumber;
console.log(hardwareId,serialNumber);//working here
});
console.log(hardwareId,serialNumber);//getting undefined here
count++;
jsonObject +='{';
jsonObject +='"hostname":"'+cam.hostname+'",';
jsonObject +='"port":"'+cam.port+'",';
jsonObject +='"hardwareId":"'+hardwareId+'",';
jsonObject +='"serialNumber":"'+serialNumber+'"';
if(count==len) {
jsonObject +="}";
} else {
jsonObject +="},";
}
});
jsonObject +=']';
res.json(JSON.parse(jsonObject));
I know that it is due to asynchronous call. Can someone look at the code and tell a better way write this.