Node Module Export Returning Undefined

2019-05-30 05:41发布

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

What am I missing?

1条回答
Juvenile、少年°
2楼-- · 2019-05-30 06:14

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

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

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;

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

查看更多
登录 后发表回答