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

标签 javascript node.js callback mongoose mocha.js

//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()(例如在我的测试用例中)。

<小时/>

//测试文件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);
    });

});

最佳答案

您可能需要像这样重新设计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 的函数将获取实际的数据。您可以在该函数中比较数据实际

关于javascript - 从回调返回一个值或在node.js 中的特定回调之外访问它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22807073/

相关文章:

javascript - Firestore - 无法编码值 - 使用 Promise.all() 和 MongoDB Insert 添加文档时

callback - 是否可以向 ZeroMQ 添加事件处理以在接收/发送数据时进行操作?

javascript - web3 立即触发回调

javascript - 嵌套循环遍历 Vue 实例中的对象数组

javascript - React superagent 的单个文件?

git - 如何在 git push(GitHub 和 node.js)之后自动部署我的应用程序?

A 中的 JavaScript : when B inherits from A, 回调看不到 B

javascript - 如何处理 Mustache 模板中的 IF 语句?

javascript - 无法在无状态组件中的现有状态转换期间更新

node.js - 使脚本与浏览器和 Node (npm)一起工作