【问题标题】:Wait for loop to complete before running further code在运行进一步的代码之前等待循环完成
【发布时间】:2022-12-10 18:31:41
【问题描述】:

这是我一直在研究的一些代码:

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);

我遇到的问题是循环之后的代码(此处为 console.log(b))在循环完成之前正在运行。

我试图让它与承诺一起工作,但无法解决。

【问题讨论】:

  • 你的问题是什么?

标签: javascript node.js es6-promise


【解决方案1】:

您面临的是因为 Promise 在 console.log(b); 完成后才完成。
解决这个问题的最简单方法就是将它包装在 async/await 中。

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

    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);
}

【讨论】:

    猜你喜欢
    • 2020-12-02
    • 1970-01-01
    • 2020-04-29
    • 1970-01-01
    • 1970-01-01
    • 2017-01-31
    • 1970-01-01
    • 2018-02-08
    • 2020-10-03
    相关资源
    最近更新 更多