【发布时间】:2015-08-12 03:23:33
【问题描述】:
我正在尝试设置我的 Flight 对象的 _docs 属性与从我的猫鼬查询返回的文档,然后根据 _docs 属性定义其他两个属性,但我无法这样做是因为它是异步发生的。我已经尝试过回调、promise 和 npm async 但我没有让它工作。
我对 JavaScript 比较陌生,在正确理解异步概念方面存在一些问题。我正在使用 node.js。
这是我想要做的:
var mongoose = require('mongoose');
mongoose.connect('mongodb://*******:******@localhost:27017/monitoring');
var db = monk('localhost:27017/monitoring', {username: '********',password: '*******'});
var VolDoc = require('./model/voldoc.js');
var Flight = function(flightId) {
this._flightId = flightId;
this._docs = VolDoc.find({_id: flightId}, {}, function(e, docs) {
return docs; //this._docs should be the same than docs!
//here or outside of the query i want do define a BEGIN and END property of the Flight Object like this :
//this._BEGIN = docs[0].BEGIN;
//this refers to the wrong object!
//this._END = docs[0].END;
});
//or here : this._BEGIN = this._docs[0].BEGIN;
//this._END = this._docs[0].END
};
var flight = new Flight('554b09abac8a88e0076dca51');
// console.log(flight) logs: {_flightId: '554b09abac8a88e0076dca51',
//_docs:
//and a long long mongoose object!!
}
我尝试了很多不同的方法。因此,当它不返回猫鼬对象时,我只得到对象中的flightId,其余的是undefined,因为程序无需等待查询完成即可继续运行。
有人可以帮我解决这个问题吗?
【问题讨论】:
-
在异步调用的情况下使用事件调度器和监听器。
标签: javascript node.js mongodb asynchronous mongoose