簡體   English   中英

如何在Node.js中停止異步執行

[英]How to stop async execution in node.js

我正在嘗試為給定的主機名動態添加IP地址。

程式碼片段

// This function will return me ip address of my server
dns.lookup('testwsserver', function (err, result {
    hostIP = result;
    console.log("Inside : "+hostIP); // Log 1
});

console.log("Outside : "+hostIP); // Log 2

var options = { 
    host    :   hostIP,
    port    :   '8080',
    path    :   null,
    method  :   'POST',
};

console.log(options); // Log 3

上面的代碼只是獲取給定主機名的IP地址並將其分配給變量“ hostIP”,問題是在循環外顯示或使用in選項時,我在hostIP中獲得了空值。

輸出-

Outside : null                          // Log 2

{ hostname: null,                      // Log 3
  port: '8080',
  path: null,
  method: 'POST',
  }

Inside : 192.168.253.18                // Log 1

根據我的需要,代碼應按順序執行,首先查找功能應將值分配給hostIP,然后再休息執行。

任何幫助表示贊賞!

正如您所說的,node.js是異步的,您必須執行以下操作:

// This function will return me ip address of my server
dns.lookup('testwsserver', function (err, result {
    hostIP = result;
    console.log("Inside : "+hostIP); // Log 1

    console.log("Inside1 : "+hostIP); // Log 2

    var options = { 
    host    :   hostIP,
    port    :   '8080',
    path    :   null,
    method  :   'POST',
    };

    console.log(options); // Log 3

});

參考下面的答案和一些修改,我得到了我的結果。.這里終於是代碼片段...

    dns.lookup('soawsserver', function (err, result) {
        hostIP = result;

// Only exception handling, in case dns look up fails to find server
        if(hostIP == null) {
            console.log("\nUnable to detect server, pl check /etc/hosts file.\n")
        }

        else {
            var options = { 
                host    :   hostIP,
                port    :   '8080',
                path    :   null,
                method  :   'POST',
            };
        };

PS:有什么更好的方法可以解決此問題,例如,不是將我的整個代碼放在查找方法中,我可以順序解決此問題嗎?

就像先運行查找方法,然后初始化我的請求一樣。

任何幫助表示贊賞!

謝謝

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM