Home > Enterprise >  Wait for loop to complete before running further code
Wait for loop to complete before running further code

Time:12-09

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.

I tried to get it to work with promises but couldn't solve it.

CodePudding user response:

What you're facing is because the Promise completes later after the console.log(b); done.
Simplest approach to solve this just by wrapping it in 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);
}
  • Related