简体   繁体   中英

How to stop async execution in node.js

I'm trying to dynamically add IP address for a given host name.

code snippet

// 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

Above code is simply fetching IP address for given hostname and assigning it to variable "hostIP", issue is that i'm getting null value in hostIP when displaying outside of loop or using in options.

Output -

Outside : null                          // Log 2

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

Inside : 192.168.253.18                // Log 1

According to my need, the code should execute in order, first lookup function should assign value to hostIP and then rest execution.

Any help is appreciated!!

As you said node.js is async you have to do as follows:

// 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

});

With reference to below answer and few modifications, i got my result.. Here is finally code snippet...

    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 : Is there any better way to solve this problem, like instead of putting my whole code in a look up method can i solve this problem sequentially?

Like first running look up method then initializing my request.

Any help is appreciated!!

Thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM