从回调中返回一个值或在node.js中的特定回调之外访问它?

时间:2014-04-02 09:27:42

标签: javascript node.js callback mongoose mocha

//geoSpacialRepository.js

var geoSpatialRepository = {};
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/repository');

var Schema = mongoose.Schema;

var LocationSchema = new Schema({
    type: String,
    coordinates: [Number,Number]
});

var Location = mongoose.model('locations', LocationSchema);

var db = mongoose.connection;

geoSpatialRepository.find = function(){
    var query = Location.find({}, function(error, data){});

    query.exec(function(err, data){
        console.log("DATA ************************** ");
        console.log (JSON.stringify(data));
    });
}

exports.geoSpatialRepository = geoSpatialRepository;

我写过console.log的地方 - >我希望该回调中的变量data,因为我将在此上下文之外调用此函数geoSpatialRepository.find()(例如,我的测试用例)。


// TestFile geoSpacilaRepository.spec.js

var assert = require("assert");

var locationsRepository = require("../geoSpatialRepository.js").geoSpatialRepository;
var chai = require("chai"),
should = chai.should(),
expect = chai.expect,
assert = chai.assert;

describe("finding locations from the database", function(){
    //setup
    var data = {
        "type":"point",
        "coordinates":[20,20]
    };
    before(function(){
        locationsRepository.save(data);
    });

    it("should find the data present in location repository",function(){
        //call
        var actual = locationsRepository.find();
        //assertion
        console.log("ACTUAL ********************"+(JSON.stringify(actual)))
        expect(actual).deep.equals(data);
    });

});

1 个答案:

答案 0 :(得分:1)

您可能需要像这样重新设计find

geoSpatialRepository.find = function(callBackFunction) {
    Location.find({}).exec(callBackFunction);
}

然后你需要从测试用例中调用它,就像这个

一样
it("should find the data present in location repository", function() {
    //call
    locationsRepository.find(function(error, data) {
        console.log("ACTUAL ********************" + (JSON.stringify(actual)))
        //assertion
        expect(actual).deep.equals(data);
    });
});

现在,作为参数传递给find的函数将获得实际的data。您可以比较该函数中的dataactual