【问题标题】:Module Export callback function returns undefined模块导出回调函数返回未定义
【发布时间】:2017-04-25 15:07:46
【问题描述】:

你好:我是 nodejs 和 mocha 的新手。我试图使用module.exports 从回调函数返回一个值。但是,它返回undefined。对于简单的情况,它虽然有效。请帮忙。

结果

  Module Export Example
    √ Test Case 1: Module
      Hello Node World!!! (*** this works - its a direct return ***)

    √ Test Case 2: Module
      undefined           (*** this fails - its from  a callback fn ***)

google.js

var requirejs = require('requirejs');       
requirejs.config({ baseUrl: '.', paths: {   }, nodeRequire: require });
describe('Module Export Example', function(){
    var mod;
    before(function(done){
        requirejs(['./googleModule'], 
            function(_mod) {
                mod = _mod;  
                done();
            });
    });  

    it('Test Case 1: Module', function(done){
        console.log(mod.get(done));
    });

    it('Test Case 2: Module', function(done){
        console.log(mod.google(done));
    });

});

googleModule.js

var request = require('request');
module.exports = {
    get: function(done){        
        var a = "Hello Node World!!!";
        return(done(), a);
    },   
    google: function(done){        
        var a = doCallback(function(){
            var b = "PRINT DATA: " + data.statusCode + ' ' + data.headers['content-type'];      
            return(done(), b);
        });
        return(done(), a);
    }
}       

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){
        var a  = callback(res, done);
        return (callback(), a); //???????
    });
}

【问题讨论】:

  • 你使用 require.js 有什么原因吗?

标签: node.js mocha.js requestjs


【解决方案1】:

因为你说你是 nodejs 和 mocha 的新手,我假设你不想做任何花哨的事情并简化你的代码。

结果

  Module Export Example
Hello Node World!!!
    ✓ Test Case 1: Module
test
PRINT DATA: 200 text/html; charset=ISO-8859-1
    ✓ Test Case 2: Module (194ms)

test/test.js

let mod = require('../googleModule');

describe('Module Export Example', function(){

    it('Test Case 1: Module', function(){
        console.log(mod.get()); // this is synchronous, no done needed
    });

    it('Test Case 2: Module', function(done){
        mod.google(function(res) {
          console.log(res);
          done(); // this is asynchronous, so we need to tell mocha when we are done
        });
        console.log('test');
    });

});

googleModule.js

let request = require('request');

module.exports = {
  get: function() {
      let a = "Hello Node World!!!";
      return a;
  },
  google: function(callback) {
    let options = {url: 'http://www.google.com', headers: {'Content-Type': 'text/html'}, encoding: null};
    request.get(options, function(err, res, body) {
        var b = "PRINT DATA: " + res.statusCode + ' ' + res.headers['content-type'];
        callback(b);
    });
  }
}

我更改了 2 个主要内容以使其正常工作。

  1. 我删除了 require.js。你不需要在 node.js 中使用它,因为已经包含了一个模块加载器。

  2. 在 javascript 中有同步和异步函数。同步函数是您从其他编程语言(如 PHP 或 Java)中了解的常规函数​​。但是,javascript 也有异步功能。不同之处在于异步函数内部的代码将在稍后执行,您不能指望它立即返回值。例如,查看测试的输出并将其与您的代码进行比较。如您所见,console.log('test');console.log(res) 之前打印,即使它低于另一个。为了处理这个问题,javascript 使用回调(或 Promises)。回调就像是告诉程序在异步函数完成后应该在哪里继续的一种方式。在您的情况下,HTTP-Request 是异步的,因此您需要告诉您的代码“等待”它完成然后打印它。 done 用于告诉 mocha 测试何时完成。

最好阅读一些关于异步函数如何工作的文章。

【讨论】:

  • 您好@Andreas Gassmann,非常感谢您花时间为我提供解决方案和解释。是的,我正在阅读这些文章,实际上其中有很多。但是作为新人,我迷失在广阔的空间中,像你这样的人为像我这样的人减轻了负担。再次感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-31
  • 1970-01-01
  • 1970-01-01
  • 2015-07-02
  • 2019-07-04
  • 1970-01-01
相关资源
最近更新 更多