ForEach之后的代码在循环完成之前运行

时间:2018-12-25 21:00:08

标签: node.js foreach

我试图获取不和谐服务器中的角色列表,查找角色所有者,其成员及其代表,但是在ForEach尚未完成之前就发生了INSERT查询...我环顾四周,所有解决方案年纪大了或将我的代码从几行变成100多行...

con.connect(function(err) {
        if (err) {
            console.log(err);
            return msg.reply({embed: {color: 16711686,description: "\\❌ | Failed to connect to database - Contact **TheeDeer**"}})
             .then(say => {
                msg.delete();
                say.delete(3000);
              });
        }
        msg.guild.roles.forEach(function(role) {
            if (role.name !== "@everyone") {
                if (role.id !== "509854902525231106" || role.id !== "509864772154687488" || role.id !== "509862522921287692" || role.id !== "526336817386225675" || role.id !== "509852743909900321" || role.id !== "526336702298456064" || role.id !== "509872838891536384" || role.id !== "509870184115339286" || role.id !== "511409235364413446" || role.id !== "509850967932665857" || role.id !== "527116001880309762" || role.id !== "509864108024397849" || role.id !== "511409106683297792" || role.id !== "526897893181882388" || role.id !== "509864540129853450" || role.id !== "509870488634523648" || role.id !== "509869899490000897" || role.id !== "511420878664237056" || role.id !== "509850657164099604" || role.id !== "526336636523380758" || role.id !== "510975537733173259" || role.id !== "509855069584490498" || role.id !== "517564552108441626" || role.id !== "509868843863244800" || role.id !== "509857751728652289" || role.id !== "510974779818377227") {
                    var ID = role.id;
                    var clanName = role.name;
                    var clanMembers = [];
                    var clanOwner = "";
                    var clanRep = [];
                    role.members.forEach( function(member, index) {
                         member.roles.forEach( function(memberRole, index) {
                            if (memberRole.id == "509869899490000897" || memberRole.id == "509881406810357792") {
                               clanOwner = member.id;
                            } else if (memberRole.id == "509870184115339286") {
                                clanRep.push(member.id);
                            } else {
                                clanMembers.push(member.id);
                            }
                        });
                    });
                    clanRep = clanRep.toString();
                    clanMembers = clanMembers.toString();
                    if (!clanMembers || !clanOwner) { failedClans.push(clanName); return; }
                    clanList.push([ID,
                        clanName,
                        clanMembers,
                        clanOwner,
                        clanRep]
                    );
                    addedClans.push(clanName)
                }
            }
        });
        await console.log(clanList);
        var sql = "INSERT INTO clans (roleID,clanName,clanMembers,clanOwner,clanRep) VALUES ?";
        con.query(sql,[clanList], function (err, result, fields) {
            if (err) {
                console.log(err);
            }
            return msg.reply({embed: {color: 16711686,description: "Added the following clans \n``` "+addedClans.toString()+" ```\n Failed to add the following ``` "+failedClans.toString()+" ```"}});
        });
    });

2 个答案:

答案 0 :(得分:0)

为解决此问题,我建议您定义自己的自定义异步版本的forEach循环。此背后的理由是您可以等待执行foreach循环,它将解决您的问题。

第1步:定义自己的forEach异步版本。

const asyncForEach = async (array, callback) => {
 for (let index = 0; index < array.length; index++) {
 await callback(array[index]);
  }
};

第2步:现在,您可以在代码中使用“ asyncForEach版本,如下所示”

await asyncForEach(msg.guild.roles, yourcallbackfunction);
con.query(.....your insert query.....);
// now if you put your Sql insert query after the above awaited asyncForEach
// it will definitely execute only once your asyncForEach execution is 
// finished.

我也遇到过类似的情况,这个foreach异步版本对我来说就像一个魅力,唯一的区别是我正在使用Elasticsearch。

快乐编码:)

答案 1 :(得分:0)

Array.forEach正在阻止,我怀疑那里可能有其他问题,即逻辑缺陷导致“ clanList”没有像您期望的那样被填充。

console.log()是一个整数计数器变量,用于在主循环的每次迭代中看到它确实在INSERT语句之前执行。