0

If I call "http://localhost:3000/?fqn=mfgthun.ch&port=80" then i get back the following string: {"source":"U259636","destination":"mfgthun.ch","ips":[]}

The resoult should be the following:
{"source":"U259636","destination":"mfgthun.ch","ips":[{"ip":"87.237.169.85","reachable":false}]}

The part in the function Write is missing... Do i need to add another callback here? Or is there any other solution for that?

Why is it not waiting until the first app.get block has finished?

const express = require('express')
const app = express()
const isReachable = require('is-reachable');

var dns = require('dns');
var os = require('os');
var url = require('url');
var jsonResponse;

function Write (ipPort, ip) {
    this.ipPort = ipPort;
    this.ip = ip;
    this.callback = function(reachable) {
        var temp = {ip: ip, reachable: reachable };
        global.jsonResponse.ips.push(temp);
    };
}

app.get("/", function(httpRequest, httpResponse, next){
    try {
        var url_parts = url.parse(httpRequest.url, true);
        var query = url_parts.query;
        global.jsonResponse = { source: os.hostname(), destination: query.fqn, ips: [] };

        dns.resolve4(query.fqn, function (err, addresses) {
            if (err) throw err;
            for(var i = 0; i < addresses.length; i++) {
                var ipPort = addresses[i] + ':' + query.port;
                var write = new Write(ipPort, addresses[i]);
                isReachable(ipPort).then(write.callback);
            };
        });
    } catch(err) {
        console.log(err);
    };
    next();
});

app.get("/", function(httpRequest, httpResponse){
    httpResponse.write(JSON.stringify(global.jsonResponse));
    httpResponse.end();
});

app.listen(3000)
DrakaSAN
  • 7,673
  • 7
  • 52
  • 94
Pascal
  • 1
  • 2
    Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – DrakaSAN Nov 03 '16 at 13:06
  • 1
    Because you mix up synchronous and asynchronous programming. – DrakaSAN Nov 03 '16 at 13:07
  • @Pascal the callback function of Write has a parameter. you didn't inform it when you call it in isReachable function. And if you want the callback function to be executed before app.get block finished, you need to return a response because it is an asynchronous function. – Ediruth Nov 03 '16 at 13:46
  • @Ediruth: thanks, found the solution with callbacks – Pascal Nov 04 '16 at 14:34

0 Answers0