1

I'm novice with javascript and I really don't know how can I get the "networks" value.

scanner.scan(function(error, networks){
   if(error) {
        console.error(error);
    } else {
        console.log(networks); << print the correct value
    }
});
console.log(networks) << print undefined

I just want to use "networks" outside function

Anyone could help me? Thanks!

Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46
carloseduleal
  • 49
  • 1
  • 7

4 Answers4

0

Add a variable before the scan function and set the value inside the function:

var netValue = null;
scanner.scan(function(error, networks){
   netValue = networks;
   if(error) {
      console.error(error);
    } else {
      console.log(networks); << print the correct value
    }
});
console.log(netValue);

The final line still may not work though if the scanner.scan() function is an asynchronous call.

jwatts1980
  • 7,254
  • 2
  • 28
  • 44
0

You can create a global value networks, and update that from within the scan function:

var globalNetworks;

scanner.scan(function(error, networks){
    globalNetworks = networks;
    if(error) {
      console.error(error);
    } else {
      console.log(networks); << print the correct value
    }
});
console.log(networks) << print the correct value

I suggest that you read about how scope works in javascript: http://www.w3schools.com/js/js_scope.asp

Isha Dijcks
  • 74
  • 11
0

The reason you cannot get the value of networks is because it is wrapped in a closure, the value is only available inside that function. Go here to read more about closures:

How do JavaScript closures work?

To have access to it outside you can create another variable outside of the function and set that to variable to network inside the function:

var otherNetworks;
scanner.scan(function(error, networks){
   otherNetworks = networks;
   if(error) {
      console.error(error);
    } else {
      console.log(networks); << print the correct value
    }
   });
 console.log(otherNetworks) << print correctValue
Community
  • 1
  • 1
omarjmh
  • 13,632
  • 6
  • 34
  • 42
0

I already did it before, but it is only showing the global value:

var globalNetworks = "global"
var scanner = wifiscanner();

    scanner.scan(function(error, networks){
      globalNetworks = networks;
      console.log(globalNetworks) //displaying all the wlan0 networks available
      if(error) {
        console.error(error);
      } else {
        // console.log(networks);
      }
    });

    console.log(globalNetworks) // displaying global

btw, networks is a json

carloseduleal
  • 49
  • 1
  • 7