如何让我的异步函数工作?打字稿

How do I get my async function to work? Typescript

我正在开发一个 discord 机器人,需要检查用户是否在我的数据库中,以便我可以为新用户创建一个配置文件。 我不熟悉使用异步函数,所以我一直在四处寻找示例,但似乎无法让它按我想要的方式工作。

使用打字稿/DiscordJS/mongoDB

let profileData;
try {
  const makeProfile = async () => {
    profileData = await profileModels.findOne({ userID: message.author.id });
    if (!profileData) {
      setTimeout(async () => {
        await new profileSchema({
          userID: message.author.id,
          serverID: message.guild?.id,
          balance: 0,
          inventory: [],
          bank: 0,
        }).save();
      }, 1000);
    }
  };
} catch (err) {
  console.log(err);
}
async function makeProfile() {
  try {
    const profileData = await profileModels.findOne({
      userID: message.author.id,
    });

    await new profileSchema({
      userID: message.author.id,
      serverID: message.guild?.id,
      balance: 0,
      inventory: [],
      bank: 0,
    }).save();
  } catch (error) {
    console.log(error);
  }
}
let profileData; // Left this in global scope in case you want to access it outside the function scope
async function makeProfile() {
  try {
    profileData = await profileModels.findOne({ userID: message.author.id });
    if (!profileData) {
      setTimeout(() => {
        await new profileSchema({
          userID: message.author.id,
          serverID: message.guild?.id,
          balance: 0,
          inventory: [],
          bank: 0,
        }).save();
      }, 1000);
    }
  } catch (err) {
    console.log(err); // Would recommend console.error for errors
  }
}

如果您关心时机,请确保在调用函数时 await


由于这是一个 discord 机器人,并且该函数似乎在 message_create 侦听器内部初始化,您可能需要考虑为 message 创建一个参数并将其移出事件侦听器。