Javascript 如何制作阻塞Mongoose.find()
我有一个对象数组,每个对象包含另一个数组。数组中每个对象的值都是一个id,需要用集合中的_id==id替换相应文档中的名称。在这种特殊情况下,NodeJS的异步特性一直是一个难题,它通过从集合中查找外部和内部数组中所有对象的数据来跟踪这些对象的数据是否已更新 实现这一点的最简单但肮脏的方法是阻塞mongoose.find()调用,该调用在当前对象中的数据更新之前不会执行前面的语句 我怎样才能做到这一点 现在就写我正试着这样做,但它不起作用Javascript 如何制作阻塞Mongoose.find(),javascript,node.js,mongodb,mongoose,Javascript,Node.js,Mongodb,Mongoose,我有一个对象数组,每个对象包含另一个数组。数组中每个对象的值都是一个id,需要用集合中的_id==id替换相应文档中的名称。在这种特殊情况下,NodeJS的异步特性一直是一个难题,它通过从集合中查找外部和内部数组中所有对象的数据来跟踪这些对象的数据是否已更新 实现这一点的最简单但肮脏的方法是阻塞mongoose.find()调用,该调用在当前对象中的数据更新之前不会执行前面的语句 我怎样才能做到这一点 现在就写我正试着这样做,但它不起作用 function getIDForName(name,
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;
}
不知道为什么这会是一种痛苦。你可以用承诺链来代替。我能想到的最好的方法可能是使用承诺