简体   繁体   English

等待 foreach 任务完成以继续

[英]wait to a foreach task be finish to continue

Hey i want to my bot send a message when the foreach is finished with the duration嘿,我想在 foreach 持续时间结束时给我的机器人发送一条消息

code:代码:


        let beforecheck = new Date();


        bot.guilds.forEach(guild => {

            //my foreach code

            }).then(() => {

            let aftercheck = new Date();

            var finished = new Discord.RichEmbed()
            .setDescription("✔ Finished ✔")
            .addField("🏓 Bot Latency", bot.ping + " ms")
            .addField("expected time", expectedtime + " minute(s)")
            .addField("final time", (60000 / (beforecheck - aftercheck)) + " minute(s)")

            message.channel.send(finished)

            })

thanks for any response感谢您的任何回应

From your code it seems like you expect the forEach to take a significant amount of time, and from the fact that you're iterating over guild s I expect that involves some sort of asynchronous Discord API calls.从您的代码来看,您似乎希望forEach花费大量时间,而从您迭代guild的事实来看,我希望这涉及某种异步 Discord API 调用。 If those are both true, forEach is the wrong tool for the job.如果这两个都是真的,那么forEach就是错误的工作工具。

If order matters : (in an async function )如果顺序很重要:(在async function

    let beforecheck = new Date();

    for(const guild of bot.guilds) { //might need bot.guilds.array()
        //use await on asynchronous calls
    }

    let aftercheck = new Date();

    var finished = new Discord.RichEmbed()
        .setDescription("✔ Finished ✔")
        .addField("🏓 Bot Latency", bot.ping + " ms")
        .addField("expected time", expectedtime + " minute(s)")
        .addField("final time", (60000 / (beforecheck - aftercheck)) + " minute(s)")

    message.channel.send(finished)

If order doesn't matter :如果顺序无关紧要

    let beforecheck = new Date();

    await Promise.all(bot.guilds.map(guild => {
        //return a promise or use async/await here
    }); //can also use .then() here but async/await is better

    let aftercheck = new Date();

    var finished = new Discord.RichEmbed()
        .setDescription("✔ Finished ✔")
        .addField("🏓 Bot Latency", bot.ping + " ms")
        .addField("expected time", expectedtime + " minute(s)")
        .addField("final time", (60000 / (beforecheck - aftercheck)) + " minute(s)")

    message.channel.send(finished)

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

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