Tuesday, 2 May 2017

Node callback from function

So, I dont fully get this yet, i know node is asuyncronous, meaning if i want to get back a variable from another module and then render it, i should use callbacks.

I think im pretty close but still not getting any resaults with this.

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

    });

});

and i pass this to another .js file to be resolved. the console.log here is always undefined and res.render wont work unless i move it another level down, but then i only get blank page.

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');
});

req.on('message', function (err, answer) {
  answer.answer.forEach(function (a) {
    console.log(a.address);
    if (a.address != undefined){
    ret = a.address;}

  });
});

req.on('end', function () {
  var delta = (Date.now()) - start;
  console.log('Finished processing request: ' + delta.toString() + 'ms');
});

req.send();
return callback(ret);

}

all the console.logs in second part of the code will print out correctly but wont bring back any values.



via Clomez

No comments:

Post a Comment