简体   繁体   English

在运行进一步的代码之前等待循环完成

[英]Wait for loop to complete before running further code

Here is some code I've been working on:这是我一直在研究的一些代码:

let b = [];

for (let i = 0; i < res.length; i++) {
  let fooFound = false;
  const foo = require(`./modules/${res[i]}`);

  rest.get(Routes.applicationCommands("BLAH")).then((c) => {

    b = c;
    
    if (b) {
      b.forEach((command) => {
        if (command.name === foo.name) {
          fooFound = true;
        }
      });

      if (fooFound === false) {
        b.push({
          name: foo.name,
          description: foo.description,
        });

      }
    }
  });

  
}

console.log(b);

The problem that I am experiencing is that the code that is after the loop (here the console.log(b) ) is running before the loop is finished.我遇到的问题是循环之后的代码(这里是console.log(b) )在循环完成之前正在运行。

I tried to get it to work with promises but couldn't solve it.我试图让它与承诺一起工作,但无法解决。

What you're facing is because the Promise completes later after the console.log(b);您面临的是因为 Promise 在console.log(b); done.完毕。
Simplest approach to solve this just by wrapping it in async/await.解决这个问题的最简单方法就是将它包装在 async/await 中。


const myProgram = async () => {
  let b = [];
  const myLoop = async () => {
   

    for (let i = 0; i < res.length; i++) {
      let fooFound = false;
      const foo = require(`./modules/${res[i]}`);

      const c = await rest.get(Routes.applicationCommands("BLAH"));
      b = c;
        
      if (b) {
        b.forEach((command) => {
          if (command.name === foo.name) {
            fooFound = true;
          }
        });

        if (fooFound === false) {
          b.push({
            name: foo.name,
            description: foo.description,
          });
        }
      }

    }
  }
  await myLoop();
  console.log(b);
}

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

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