NodeJS,即使完成后函数调用也没有返回undefined

时间:2017-04-24 21:49:17

标签: node.js mocha requestjs

您好:我是nodejs和mocha的新手。我正在努力处理函数调用的返回值。它总是回归' undefined'即使(我认为)我已经适当地使用了回调()。

在下面的示例中,我如何确保get()的返回值始终返回正确的值而不是“未定义”。在此功能中,我使用requestJS模块打开google.com并返回内容类型。但是,它当前返回undefined。

非常感谢!

更新了帖子后反馈:

  • 包含Test Case 3示例,以实施Callback结果是:我现在可以根据需要打印数据。但是,我得到并且错误告诉我调用done()。我做错了什么?

结果在节点终端上运行

 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)

    PRINT DATA: 200 text/html; charset=ISO-8859-1
    √ Test case 3 
    Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.
    ...

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

    it('Test Case 3', function(){
        doCallback(callbackHandler);  
    });

});

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

function callbackHandler(data) {
    console.log("PRINT DATA: " + data.statusCode + ' ' + data.headers['content-type']);  
}

function doCallback(done){
    var options = {url: 'http://www.google.com', headers: {'Content-Type': 'text/html'}, encoding: null};     
    request.get(options, function(err, res, body){           
        var finalData = res;        
        return done(finalData); 
    }); 
}

1 个答案:

答案 0 :(得分:0)

一种可能的解决方案(使用回调)

var request = require('request');

describe('suite', function(){
    it('Test Case 3', function(done){
        doCallback(callbackHandler, done);  
    });

    it('Test Case: 3A', function(done){
        doCallback(function(data){
        console.log("PRINT DATA: " + data.statusCode + ' ' + data.headers['content-type']);  
        done();        
    });  
});     

});

function callbackHandler(data, done) {
    console.log("PRINT DATA: " + data.statusCode + ' ' + data.headers['content-type']);  
    done();
}

function doCallback(callback, done){
    var options = {url: 'http://www.google.com', headers: {'Content-Type': 'text/html'}, encoding: null};     
    request.get(options, function(err, res, body){           
        return callback(res, done); 
    }); 
}

一种可能的解决方案(使用承诺)

var request = require('request');

describe('suite', function () {
    this.timeout(10000);
    it('Test Case 3', function () {
        return doCallback()
            .then(function (res) {
                console.log(res.statusCode + " " + res.headers['content-type']);
            })
            .catch(function(res){
                console.log(res);
            });
    }); });

function doCallback() {
    return new Promise(
        function (resolve, reject) {
            var options = { url: 'http://www.google.com', headers: { 'Content-Type': 'text/html' }, encoding: null };
            request.get(options, function (err, res, body) {
                if (err)
                    reject(err); 
                else 
                    resolve(res);
            });
        }
    ); }