节点模块导出返回未定义 [英] Node Module Export Returning Undefined

查看:99
本文介绍了节点模块导出返回未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个节点模块来获取一些帖子,但是却收到未定义的错误.

I am trying to create a node module to grab some posts but I am getting an undefined error.

Index.js

var request = require('request');

function getPosts() {

  var options = {
    url: 'https://myapi.com/posts.json',
    headers: {
      'User-Agent': 'request'
    }
  };

  function callback(error, response, body) {
    if (!error && response.statusCode == 200) {
      return JSON.parse(body);
    }
  }

  request(options, callback);
}

exports.posts = getPosts;

test/index.js

var should = require('chai').should(),
    myModule = require('../index');

describe('Posts call', function () {
  it('should return posts', function () {
    myModule.posts().should.equal(100);
  });
});

我想念什么?

推荐答案

===纠正错字后进行了编辑===

=== edited after the typo was corrected ===

看起来您实际上并没有了解"回调的工作原理.

Looks like you don't actually "get" how callbacks work.

您定义的回调将异步触发,因此它实际上不能用于以您尝试的方式返回值.做到这一点的方法是让您的getPosts()函数实际上接受另一个函数,这就是调用代码关心的回调.因此您的测试将如下所示:

The callback you defined will fire asynchronously, so it can't actually be used to return a value the way you're trying to. The way to do it is to have your getPosts() function actually accept another function to it, which is the callback that the calling code cares about. So your test would look something like this:

describe('Posts call', function(){
  it('should have posts', function(done){
    myModule.posts(function(err, posts){
      if(err) return done(err);
      posts.should.equal(100);
      done();
    });
  }
});

然后,您的模块代码应如下所示:

then your module code would be something like this, in order to support that:

var request = require('request');

function getPosts(callback) {

  var options = {
    url: 'https://myapi.com/posts.json',
    headers: {
      'User-Agent': 'request'
    }
  };

  function handleResponse(error, response, body) {
    if (!error && response.statusCode == 200) {
      return callback(null, JSON.parse(body));
    }
    return callback(error); // or some other more robust error handling.
  }

  request(options, handleResponse);
}

exports.posts = getPosts;

那里可能会有更好的错误处理方式,例如确保JSON.parse正确运行,但这应该可以给您带来启发.

There could be better error handling in there, like making sure the JSON.parse works right, but that should give you the idea.

这篇关于节点模块导出返回未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆