【问题标题】:How do I get my async function to work? Typescript [duplicate]如何让我的异步功能工作?打字稿[重复]
【发布时间】:2022-01-26 11:34:38
【问题描述】:

我正在开发一个不和谐的机器人,需要检查用户是否在我的数据库中,以便我可以为新用户制作个人资料。 我是使用异步函数的新手,所以我一直在寻找示例,但似乎无法让它按我想要的方式工作。

使用 Typescript / 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);
}

【问题讨论】:

  • 呃,你从来没有打电话给makeProfile

标签: javascript typescript asynchronous async-await discord.js


【解决方案1】:
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);
  }
}

【讨论】:

  • 非常感谢!完美运行
  • 这虽然缺少 1s 延迟
【解决方案2】:
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


由于这是一个不和谐的机器人,并且该函数似乎在 message_create 侦听器中进行了初始化,因此您可能需要考虑为 message 创建一个参数并将其移出事件侦听器。

【讨论】:

    猜你喜欢
    • 2018-05-10
    • 2017-02-03
    • 2018-09-29
    • 1970-01-01
    • 2021-07-04
    • 2021-08-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多