나는 nodegs를 사용하여 Mongoose에서 Mongoose의 데이터를 쿼리합니다. 데이터를 얻은 후에 클라이언트에 응답하기 전에 데이터에 대해 작업을 수행해야합니다. 그러나 나는 반환 가치를 얻을 수 없다. Google에서 살펴본 후 Node.js 함수가 비동기 자바 스크립트 함수 (비 I/O 차단)임을 알게되었습니다. 나는이 혀를 (http://www.youtube.com/watch?v=xDW9bK-9pNY) 시도하지만 그것은 작동하지 않습니다. 아래는 제 코드입니다. myObject는 "find()"함수 내부에서 평가되고 "find()"함수 외부에서 정의되지 않습니다. 그렇다면 데이터를 얻으려면 어떻게해야합니까? 감사!Nodejs의 비동기 함수에서 반환 값
var Person = mongoose.model('Person', PersonSchema);
var Product = mongoose.model('Product', ProductSchema);
var myObject = new Object();
Person.find().exec(function (err, docs) {
for (var i=0;i<docs.length;i++)
{
Product.find({ user: docs[i]._id},function (err, pers) {
myObject[i] = pers;
console.log(myObject[i]); //return the value is ok
});
console.log(myObject[i]); //return undefined value
}
console.log(myObject); //return undefined value
});
console.log(myObject); //return undefined value
app.listen(3000);
console.log('Listening on port 3000');
이것은 내 github 게시물입니다 : https://github.com/LearnBoost/mongoose/issues/1706#issuecomment-24887415 –