[英]Node.js driving things in right order in basic code
我在node.js异步世界中挣扎,我在node.js中是菜鸟。 我不了解如何推动基本程序流程。 我使用软件包iotdb-arp在网络上打印ip地址和mac地址。 我需要运行此代码,执行功能扫描,等到变量arr满后再打印该arr和结束消息。 我知道我应该使用回调,但是我真的迷路了。 有人可以指出我正确的方向,如何以正确的顺序进行工作吗? 现在,当我执行它时显示“ [+] Program start”,然后显示“此机器的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"
“浏览器”调用中的功能参数是回调。 这意味着,当“浏览器”函数结束时,它将调用您插入的参数函数。 这是您在“扫描”功能中必须要做的。
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"
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.