【问题标题】:How can i recode this function to actually await the results within我如何重新编码此函数以实际等待其中的结果
【发布时间】:2020-08-10 10:03:48
【问题描述】:

所以基本上我知道我的代码问题出在哪里

export async function hourlyUpdate(bot:Discord.Client){
    let result=new Promise<ActiveSubscriberList>(async (resolve,reject)=>{
        let fileData=await getDataFromFile()
        let resultList:ActiveSubscriberList={Server:[]}
        fileData.channels.forEach(async(element,index)=>{
            let tempArr=[]
            element.subscriber.forEach(element => {
                tempArr.push(element.userID)
            })
            let tempEntry={Channel:element.channelID,Subscriber:await actualFetch(bot,element.guildID,tempArr)}
            resultList.Server.push(tempEntry)
        })

        resolve(resultList)
    }).then(value=>{

    })
    return result

}
async function actualFetch(bot:Discord.Client,guildID:string,userArr:string[]){
    let result= new Promise<string[]>(async (resolve)=>{
        let activeSubs=[]
        let tempSubArray=await bot.guilds.cache.get(guildID).members.fetch({ user: userArr, withPresences: true })
        tempSubArray.forEach(element=>{
            activeSubs.push(element.user.id)
        })
        resolve(activeSubs)
    })
    return result
}

我认为问题在于循环继续,尽管其他异步函数的结果没有得到解决。

我的问题是,是否有人知道如何重新编码这些循环,以便整个函数实际上返回结果而不是空对象。任何其他有关如何使此代码更好的 cmets、提示和建议也值得赞赏。

【问题讨论】:

标签: typescript async-await discord.js


【解决方案1】:

forEach 中的 await 意味着内部的 Promise 没有与外部的任何东西链接。相反,请使用 .map 以便将所有结果作为 Promises 数组,然后在该数组上调用 Promise.all

你也应该避免explicit Promise construction antipattern:

export async function hourlyUpdate(bot: Discord.Client) {
  const fileData = await getDataFromFile();
  const Server = await Promise.all(fileData.channels.map(async (element) => {
    const tempArr = element.subscriber.map(element => element.userID);
    const Subscriber = await actualFetch(bot, element.guildID, tempArr);
    return { Channel: element.channelID, Subscriber };
  }));
  return { Server };
}
async function actualFetch(bot: Discord.Client, guildID: string, userArr: string[]) {
  const tempSubArray = await bot.guilds.cache.get(guildID).members.fetch({ user: userArr, withPresences: true });
  return tempSubArray.map(element => element.user.id);
}

当您不打算重新分配变量时,请记住使用const,而不是let,当您想通过转换另一个数组的所有元素来构造数组时,.map 是合适的方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-03
    • 1970-01-01
    相关资源
    最近更新 更多