Node.js在基本代码中按正确的顺序驱动事物



我在node.js的异步世界中挣扎,我对node.js一无所知。我不知道如何驱动基本的程序流。我使用包iotdb-arp在网络上打印ip地址和mac地址。我需要运行这段代码,执行函数扫描,等待变量arr满,然后打印arr和结束消息。我知道我应该使用回调,但我真的很失落。有人能给我指一个正确的方向吗?如何按正确的顺序处理事情?现在,当我执行它打印"[+]程序启动"时,它打印"这台机器的IP是:192.168.1.2",然后扫描被执行,但程序最终同时执行,arr为空,因为扫描仍在运行。这是我的代码:

console.log("[+] Program start");
var ip = require('ip');
var browser = require('iotdb-arp');
var arr = [];
var myIp = ip.address();
console.log("IP of this machine is : " + myIp.toString());
function scan(){
browser.browser({},function(error, data) {
if (error) {
console.log("#", error);
} else if (data) {
console.log(data);  
arr.push(data); 
} else {
}    
});
}
/*function callback(){
console.log(arr);  
console.log("[+] Program End");
}*/
scan();
console.log(arr); // Here in the end i need print arr
console.log("[!] Program End"); // Here I need print message "[+] Program End"

"browser"调用中的函数参数是回调。这意味着当"浏览器"函数结束时,它正在调用您插入的参数函数。这是您在"扫描"功能中必须执行的操作。

console.log("[+] Program start");
var ip = require('ip');
var browser = require('iotdb-arp');
var arr = [];
var myIp = ip.address();
console.log("IP of this machine is : " + myIp.toString());
function scan(callb){
browser.browser({},function(error, data) {
if (error) {
console.log("#", error);
callb(err);
} else if (data) {
console.log(data);  
arr.push(data); 
} else {
callb()
}    
});
}

scan(function(err){
if(err) {return;} /// handle error here
else {
console.log(arr); // Here in the end i need print arr
console.log("[!] Program End"); // Here I need print message "[+] Program End"
}

});

最新更新