我正在编写一个 Discord.js 机器人来连接到网站并充当门户。我写了一个叫做 getUser 的函数,用于所有其他函数,当它被调用时,它从不等待。
function getUser(message) {
let user;
if (!data.userAcc.hasOwnProperty(message.author)) return null;
for (let i=0;i<Object.keys(data.userAcc).length;i++) {
if (Object.keys(data.userAcc)[i]==`<@${message.author.id}>`) {
MongoClient.connect(config.mongoURI,{useUnifiedTopology:true},(err,db)=>{
if (err) throw err;
let dbo=db.db("knoldus");
dbo.collection("users").findOne({"user.email":Object.values(data.userAcc)[i]},(err,result)=>{
if (err) throw err;
if (result==null||result==undefined) {
delete data.userAcc[i]
return 'error:no-email'
}
console.log(result);
return result;
});
})
}
}
}
async function checkStatus(message) {
let user = await getUser(message);
console.log("user: "+user);
if (user==null) return message.channel.send(`You are not logged in ${message.author}!`);
if (user=='error:no-email') return message.author.send(`Cannot find the email **${Object.values(data.userAcc)[i]}** ${message.author}! The account may have been deleted.`);
return message.channel.send(`${message.author}'s status: ${user.user.dispatchStatus} | Set by: ${user.user.dispatchStatusSetBy}`);
}
输出显示 getUser 正在工作,但调用它的函数不会等待它完成。 这是输出
user: undefined
{
my user object
}
从 getUser
打印的对象发生在主函数 getStatus
之后,没有完成 getUser