我正在处理一个聊天项目,NodeJS必须等待25秒才能从MongoDB获得新数据,我可以在While循环中实现它,我想听听其他人的建议。
while(true) {
db.messages.find({
...
}).then(result) => {
if (result.length > 0) {
return result;
}
})
}
顺便说一句,我的方法不好吗?
更新:
另一种方式...
let secs = 0;
const iv = setInterval(() => {
secs++;
db.messages.find({
...
}).then(result) => {
if (result.length > 0) {
clearInterval(iv);
res.json(result);
return;
}
});
if (secs === 25)
clearInterval(iv);
}, 1000);
答案 0 :(得分:1)
const collection = db.collection('messages');
const changeStream = collection.watch();
changeStream.on('change', next => {
// process next document
});