Monday, 24 April 2017

NodeJS, function call not returning undefined even after done

Hello: i am new to nodejs and mocha. I am struggling with the return value from a function call. It is always returning 'undefined' even though (i think) i have used the callback done() appropriately.

In the following example, how can i ensure that the return value from get() always returns the correct value and not 'undefined'. In this function, I have used the requestJS module to open google.com and return the content-type. However, it currently returns undefined.

Thanks a lot!

Result post running on node terminal

 suite
    PRINT DATA: 200 text/html; charset=ISO-8859-1
    √ Test case 1 (607ms)

    undefined (<< ****** how to return the correct value?** )
    PRINT DATA: 200 text/html; charset=ISO-8859-1
    √ Test case 2 (603ms)

Google.js

var request = require('request');

describe('suite', function(){
    it('Tase case 1', function(done){
        var options = { url: 'http://www.google.com', headers: {'Content-Type': 'text/html'}};     
        request.get(options, function (err, res, body){
            console.log("PRINT DATA: " + res.statusCode + ' ' + res.headers['content-type']);  
            //do some stuff here                        
            done();
        });        
    });

    it('Test case 2', function(done){
        console.log(get(done));
    });

});

function get(done){
    var options = {
        url: 'http://www.google.com',
        headers: {'Content-Type': 'text/html'},
        encoding: null
    };     
    request.get(options, function(err, res, body){
        console.log("PRINT DATA: " + res.statusCode + ' ' + res.headers['content-type']);  
        //do some stuff here                    
        return done(), res.headers['content-type'];        
    }); 
}



via Bipo K

No comments:

Post a Comment