Node Module Export Returning Undefined

一世执手 提交于 2019-12-08 08:32:47

问题


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:


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



来源:https://stackoverflow.com/questions/26291204/node-module-export-returning-undefined

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