我有一个对象数组,每个对象包含另一个数组。数组中每个对象的值是一个id,需要在集合中带有_id == id的相应文档中的Name替换。在这种特殊情况下,NodeJS的异步性质一直很痛苦,并且通过从集合中查找它们来跟踪外部和内部数组中的所有对象的数据是否已经更新。
实现这一目标的最简单但最脏的方法是使用BLOCKING mongoose.find()调用,该调用在当前对象中的数据更新之前不会执行前面的语句。
我怎样才能做到这一点?
现在写我试图这样做,但它没有用。
function getIDForName(name, callBackMethod) {
var _id = null;
var breakTheLoop = false;
const thread = spawn(function() {
// Everything we do here will be run in parallel in another execution context.
// Remember that this function will be executed in the thread's context,
// so you cannot reference any value of the surrounding code.
CircleTimeSong.getCircleTimeSongModelObject().find({songName:name}, function(err, foundData) {
console.error("callback");
if (err) {
console.error("error in getIDForName CircleTimeSongController.js: ", err);
//callBackMethod(null);
breakTheLoop = true;
}
console.log("found data length: ", foundData.length);
if (foundData != null && foundData.length > 0) {
console.log("doku 3", foundData[0]._id);
_id = foundData[0]._id;
breakTheLoop = true;
}
//callBackMethod(_id);
});
});
while(true) {
//console.log("in loop");
if(breakTheLoop)
break;
}
thread.kill();
return _id;
}