【问题标题】:Returning a value from callback or accessing it outside that particular callback in node.js?从回调返回值或在 node.js 中的特定回调之外访问它?
【发布时间】:2014-05-13 11:28:00
【问题描述】:
//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);
    });

});

【问题讨论】:

  • 您的意思是,如果您调用geoSpatialRepository.find(),则必须返回data
  • 是的。在那个回调之外!

标签: javascript node.js callback mongoose mocha.js


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-31
    • 1970-01-01
    相关资源
    最近更新 更多