While I have been working in python
for quite some time, I've recently started working with javascript
for its tight integration with Web.
I am still struggling with concepts of event driven programming and promise driven function.
Anyway, Below I am using node.js
module is-port-reachable.
It does a good job of returning status if given host is reachable over a given port or not.
However, I need to collect combined info of host and port status.
For e.g. if I have hosts = ['hostA' , 'hostB' ];
I need to collect status of its port scan status as
hosts2 = [ ('hostA' , true) , ('hostB', false)];
With below code, I am able to get individual status of port scan for each host, but when I try to add it to array host2
, its coming back as empty.
It seems promise function is not able to take/recognize external variable aHost
.
const isPortReachable = require('is-port-reachable');
hosts = [ 'host' , 'host2'];
var hosts2 = new Array();
for ( var l = 0; l < hosts.length; l++) {
var aHost = hosts[l];
const myFunction = (aHost) =>{
return isPortReachable(8443, {host: aHost})
};
myFunction(aHost).then(result => {
console.log(aHost, result);
hosts2.push((aHost,result));
});
}
console.log(hosts2);
Output:
Further, Looks like console.log(hosts2);
is getting executed before for loop.
node myscript.js
[]
hostA true
hostB false
Any help is appreciated.