[英]Node.js driving things in right order in basic code
I am struggling with node.js asynchronous world, I am noob in node.js. 我在node.js异步世界中挣扎,我在node.js中是菜鸟。 I don't understand how to drive basic program flow.
我不了解如何推动基本程序流程。 I use package iotdb-arp to print ip adress and mac adress on network.
我使用软件包iotdb-arp在网络上打印ip地址和mac地址。 I need to run this code, execute function scan, wait until variable arr is full then print that arr and ending message.
我需要运行此代码,执行功能扫描,等到变量arr满后再打印该arr和结束消息。 I know that I should use callbacks but I am really lost.
我知道我应该使用回调,但是我真的迷路了。 Could someone point me to right direction, how to run things in right order?
有人可以指出我正确的方向,如何以正确的顺序进行工作吗? Now when I execute that it prints "[+] Program start", then it prints "IP of this machine is : 192.168.1.2" then scan is executed but program is simultaneously in the end, arr is empty because scan is still running.
现在,当我执行它时显示“ [+] Program start”,然后显示“此机器的IP为:192.168.1.2”,然后执行扫描,但程序同时结束,arr为空,因为扫描仍在运行。 Here is my code:
这是我的代码:
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"
The function parameter in the "browser" call is a callback. “浏览器”调用中的功能参数是回调。 Which means that when the "browser" function end , it is calling the parameter function you inserted.
这意味着,当“浏览器”函数结束时,它将调用您插入的参数函数。 This is what you have to do in your "scan" function.
这是您在“扫描”功能中必须要做的。
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.