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!
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.
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
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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.