立即解决 Mongoose Promise 调用
发布时间:2022-08-09 13:48:00 230
相关标签:
我的代码在代码末尾执行 Promiseconst voters = Player.countDocuments({})行,但我需要它立即解析,以便可以在其余代码中使用它的值。
我该怎么做才能让它基本上作为同步线运行?我曾尝试使用函数来分离代码,将其从套接字中取出,使用 async/await,使用 .resolve().then() 等,但它总是在我想统计选票后解决。
io.on('connection', (socket) => {
socket.on('direction vote', (individualVote) => {
var voteCount = 1;
var yesVotes = 1;
// count the number of players that will be in the game
const voters = Player.countDocuments({})
.then((voterCount) =>{console.log('voterCount: ' + voterCount);});
// receive the votes and tally them
if (individualVote == 'yes') {
yesVotes ++;
voteCount ++;
console.log('yesVotes: ' + yesVotes);
};
console.log('voters: ' + voters); // this resolves as the promise's object
if (voteCount == voters) {
// stuff happens
// send the vote results to everyone
io.emit('direction vote result', voteResult);
};
});
});
编辑:根据Bergi的评论,这就是我使用async/await的方式。
io.on('connection', (socket) => {
socket.on('direction vote', (individualVote) => {
var voteCount = 1;
var yesVotes = 1;
** // count the number of players that will be in the game
async function count() {
const countVoters = await Player.countDocuments({});
console.log('countVoters: ' + countVoters);
return countVoters;
}
var voters = count();
console.log('voters: ' + voters);
**
// receive the votes and tally them
if (individualVote == 'yes') {
yesVotes ++;
voteCount ++;
console.log('yesVotes: ' + yesVotes);
};
console.log('voters: ' + voters); // this resolves as the promise's object
if (voteCount == voters) {
// stuff happens
// send the vote results to everyone
io.emit('direction vote result', voteResult);
};
});
});
特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报