Node Module Export Returning Undefined

╄→尐↘猪︶ㄣ 提交于 2019-12-06 16:38:26

=== 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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!