Sunday, 7 May 2017

Node callback function not working at all after fix

i had problem with my callback function not working and asked for help here in stack. I fixed my code according to the answer, but now the function is totally broken. i don't get any console.logs anymore and i have no idea why... Might just be some stupid mistake but anyways, here is my

server.js

app.get('/lookup', function (req, res) {
        lookup("www.google.com", function (err, result) {
        if (err) { return console.error(err);
        console.log(result); ;}})
        else{res.render("layout_lookup", { lookup: result });}


    });

And here is the actual module for my app.

Lookup.js

module.exports = lookup;

var dns = require('native-dns');
var util = require('util');
var ret;

function lookup(url, callback) {

    var question = dns.Question({
        name: url,
        type: 'A',
    });

    var start = Date.now();

    var req = dns.Request({
        question: question,
        server: { address: '8.8.8.8', port: 53, type: 'udp' },
        timeout: 1000,
    });

    req.on('timeout', function () {
        console.log('Timeout in making request');
        // RETURN ERROR OBJECT; SEND RESPONSE AS EMPTY
        return (new Error('Timeout!'),null);
    });

    req.on('message', function (err, answer) {
        answer.answer.forEach(function (a) {
            console.log(a.address);
            if (a.address != undefined) {
                ret = a.address;
                // RETURN ERROR AS NULL AND RESPONSE AS RET
                return (null,ret);
            }

        });
    });
    return (null, ret);
}



via Clomez

No comments:

Post a Comment