我的异步在等待呼叫中返回未定义

时间:2019-07-03 17:43:50

标签: javascript bots discord discord.js

我正在使用Discord.js机器人,我有一个应该在数组中循环并获得Sequelize为每个元素返回的对象的函数。应该将每个值都放在一个映射中,然后返回该映射。但是它总是返回undefined。

class top {
  async run (client, msg, args) {
    const member = msg.member

    let factionName = args[1]
    for (let index = 2; index < args.length; index++) {
      factionName += ' ' + args[index]
    }

    const embed = await topFaction(msg, member, factionName)

    msg.channel.send(embed)
  }
}

async function topFaction (msg, member, factionName) {
  const embed = new Discord.RichEmbed()
    .setTitle(member.displayName)
    .setFooter(member.displayName + '#' + member.user.discriminator, member.user.avatarURL)

  const actualSeason = await SeasonManager.getActualSeason()
  if (!actualSeason) return embed.setDescription(`Aucun saison n'est en cours.`).setColor('RED')

  if (!factionName) return embed.setDescription(`Vous devez entrer le nom d'une faction.`).setColor('RED')

  const faction = await FactionManager.getFaction(factionName)
  if (faction) {
    const users = await faction.getUsers()
    if (users.length === 0) return embed.setDescription('La faction est vide.').setColor('RED')

    const xpMap = await getXPMap(users)
    console.log('xpMap - ' + xpMap) // Is undefined
    return embed.setDescription('Classement').setColor('BLUE')
  } else {
    return embed.setDescription(`La faction ${factionName} n'existe pas.`)
      .setColor('RED')
  }
}

async function getXPMap (users) {
  let xpMap = new Map()
  syncEach(users, async function (user, next) {
    const actualXP = await ExperienceManager.getActualExperiences(user)
    if (actualXP) xpMap.set(user.get('discordID'), actualXP.get('count'))
    next(null)
  },
  function (err) {
    if (err) logger.log('error', err)
    console.log(xpMap) // Not undefined
    return xpMap
  })
}

除了getXPMap()返回填充的地图外,我没有定义。

1 个答案:

答案 0 :(得分:0)

因为sincEach有点怪异的功能(幸运的是,我不知道它的源代码很简单),我把它全部包装在Promise中以在回调中解决

async function getXPMap (users) {
 return new Promise((resolver)=>{
  let xpMap = new Map()
  syncEach(users, async function (user, next) {
    const actualXP = await ExperienceManager.getActualExperiences(user)
    if (actualXP) xpMap.set(user.get('discordID'), actualXP.get('count'))
    next(null)
  },
  function (err) {
    if (err) logger.log('error', err){
    console.log(xpMap) // Not undefined
    }
     resolver(xMap)
  })
 
 })
 
}

相关问题