简体   繁体   English

如何在没有异步的情况下使用等待 mongoose

[英]How to use await mongoose without async

I have this code where I fetch a list of elements so I can make discordjs options with the mongoose data我有这段代码,我在其中获取元素列表,因此我可以使用 mongoose 数据创建 discordjs 选项

const items = require(‘./schema.js’)
    const items1 =  await items.find()


module.exports = {
    name: `buy`,
    timeout:15000,
    /**
     * @param {Client} client
     * @param {Message} message
     * @param {String[]} args
     */
    data: new SlashCommandBuilder()
.setName('buy')
.setDescription('buy an item!')
.addStringOption(option =>
    option
    .setName('itemid')
    .setDescription('the item you want to buy')
    .setRequired(true)
   /**   .addChoices(
        items1.forEach(item => {
            option.addChoice(`<:${item.EmojiName}:${item.EmojiID}>${item.ItemName} - <:bobux:809551218217058354>${item.Price} `,`${item.ItemID}` )
        })
    )
    */

    ),

When I do this, I get the error that you can't use await outside of async.当我这样做时,我得到你不能在异步之外使用 await 的错误。 Does anyone have any solutions/alternatives to this code?有人对此代码有任何解决方案/替代方案吗?

Thanks谢谢

The situation you're facing is more like a bad-design symptom than a limitation.您面临的情况更像是设计不良的症状,而不是限制。 What you are actually trying to do is "generating Discord commands — asynchronously — based on Mongoose data".您实际上要做的是“基于 Mongoose 数据异步生成 Discord 命令”。

Well, just do that in the code.好吧,只需在代码中执行此操作。 Don't try to mix and export synchronously an asynchronously generated thing.不要尝试同步混合和export异步生成的东西。 Rather simply make a function that generates it:而是简单地制作一个 function 来生成它:

const Item = require('./schema.js')

const itemToChoice = item => `<:${item.EmojiName}:${item.EmojiID}>${item.ItemName} - <:bobux:809551218217058354>${item.Price} `
const addItemsChoices = (option, items) => (
  items.reduce((option, item) => (
    option.addChoice(itemToChoice(item),`${item.ItemID}`)
  ), option)
)

module.exports = async () => {
  const items =  await Item.find()

  const command = {
    name: `buy`,
    timeout:15000,
    /**
     * @param {Client} client
     * @param {Message} message
     * @param {String[]} args
     */
    data: new SlashCommandBuilder()
      .setName('buy')
      .setDescription('buy an item!')
      .addStringOption(option => (
        addItemsChoices(
          option
            .setName('itemid')
            .setDescription('the item you want to buy')
            .setRequired(true),
          items
        )
      ))
  }

  return command
}

PS: for god sake, format your code PS:看在上帝的份上,格式化你的代码

PS2: for god sake, remove smart punctuation on your computer PS2:看在上帝的份上,去掉你电脑上的智能标点符号

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM