2017-02-02 12 views
0

我在node.js異步世界中苦苦掙扎,我在node.js中選擇noob。我不明白如何驅動基本的程序流程。我使用軟件包iotdb-arp在網絡上打印IP地址和MAC地址。我需要運行這段代碼,執行函數掃描,等到變量arr已滿,然後打印該arr並結束消息。我知道我應該使用回調,但我真的很失落。有人能指引我正確的方向,如何按正確的順序運行?現在當我執行它打印「[+]程序啓動」,然後它打印出「本機的IP爲:192.168.1.2」,然後執行掃描,但程序同時結束,因爲掃描仍在運行,所以arr爲空。這裏是我的代碼:Node.js在基本代碼中以正確的順序驅動事物

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" 
+0

你不能那樣做。你需要使用回調。 – SLaks

回答

0

「瀏覽器」調用中的函數參數是一個回調函數。這意味着當「瀏覽器」功能結束時,它會調用您插入的參數功能。這是您在「掃描」功能中必須執行的操作。

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" 
} 


}); 
+0

謝謝Dion,它好多了,但它看起來像callb()被執行了2次。所以我得到了「[!]程序結束」2次。這是我的輸出的簡短示例:{ip:'192.168.1.1', mac:'9C:5C:8E:C7:44:88', interface : 'EN0', 看出:1486054726758} 程序結束 {IP [!]: '192.168.1.1', MAC: '9C:5C:8E:C7:44:88', 接口: 'EN0', 看過:1486054729261} [!]程序結束 – Mischa