我如何等待查询返回结果,然后分配给JSON数组

我正在使用node / express / mongoose / mongodb ,并收集了一些“数据包”。 用户可以单独设置“数据包”的状态,我试图向他们展示所有数据包的列表,并向他们显示它们为数据包设置的状态。 我一直在这个工作了几天,不能使其正确的工作。

我想要发生的是,我必须查询第一个列表,然后遍历结果数组,并添加结果,如果有结果的第一个数据包。

这似乎是closures问题或只是返回结果的时间问题。 不pipe我想出了什么样的作品。

谢谢,

这是我的位置:

var Packet = mongoose.model('Packet', new Schema({ id: ObjectId, userId: String, //whom originally posted packet courseId: {type: Schema.ObjectId, ref: 'Course', index: true, required: true }, content: {type: String, index: true}, status: String, date: {type: Date, default: Date.now}, mostRecentEdit: {type: Date, default: Date.now} })); var History = mongoose.model('History', new Schema({ id: ObjectId, userId: String, status: {type: String, index: true, required: true, default: 1}, courseId: {type: Schema.ObjectId, ref: 'Course', required: true }, clickCounter: {type: Number, default: 1}, packetId: {type: Schema.ObjectId, ref: 'Packet', required: true }, date: {type: Date, default: Date.now} })); app.get('/api/packets/:_id', stormpath.groupsRequired(['Paid']), stormpath.getUser, function(req, res, next){ var status; var pack; var newStatus; try{ Packet.find({courseId: req.params._id}) .exec( function(err, packets){ pack = packets; for (i = 0; i < pack.length; i++){ var promise = History.findOne({ packetId: pack[i]._id, userId: req.user.email }) .select('status') .exec( function(err, package){ if(package == null){ status = 1 } else { status = package.status; }; newStatus = status }); promise.then(pack[i].status = newStatus); }; res.json(pack)} }); }catch(err){ next(err); }; });