1

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.

Susheel Singh
  • 3,824
  • 5
  • 31
  • 66
  • 1
    The variables are accessible outside of the function, but before calling the function their value will be `undefined`. – Tushar Mar 19 '16 at 10:58
  • It looks like your callback is never executed, or that `b._` is undefined. Try adding `console.log("Calling callback", a, b, c)` in the callback body and see if it comes out. It is also possible that `cam.getDeviceInformation` works asynchronously - it may return immediately, then you log undefineds, and then the callback is called. – Wojciech Ptak Mar 19 '16 at 10:58
  • 1
    `.getDeviceInformation` appears to return results asynchronously , where `console.log()` is called before `.getDeviceInformation` callback completes ? You could pass `serialNumber` as parameter to another function call, or perform `console.log()` or other task within `getDeviceInformation` callback ? – guest271314 Mar 19 '16 at 11:00
  • can someone look at my code and help me solve the problem – Susheel Singh Mar 19 '16 at 11:23

1 Answers1

0

It's possible, but if the function passed to getDeviceInformation is not called synchronously then the variables would still be undefined at the time when your console.log is called.

In other words - it's not an issue of accessibility, but rather of timing.

obe
  • 7,378
  • 5
  • 31
  • 40