while循环麻烦

时间:2018-06-27 07:45:32

标签: javascript node.js while-loop

我正在尝试在我的util()函数中使用while循环(其注释在代码底部)。当我尝试运行程序时,我陷入了一个无尽的循环,在这个循环中,我没有比控制台登出“ getProjects running”的地方更远的地方

const axios = require("axios");
const _ = require("lodash");

axios.defaults.headers.common["Private-Token"] = "iTookMyPrivateKeyOut";
const user = "yshuman1";
let projectArray = [];
let reposExist = true;

async function getProjects() {
  console.log("getProjects running");
  await axios
    .get(`https://gitlab.com/api/v4/users/${user}/projects`)
    .then(function(response) {
      const arr = _.map(response.data, "id").forEach(repo => {
        projectArray.push(repo);
      });
      console.log(projectArray);
    });
}

function deleteRepo(projectArray) {
  console.log("array size", projectArray.length);
  const arr = _.map(projectArray).forEach(item => {
    axios
      .delete(`https://gitlab.com/api/v4/projects/${item}`)
      .then(() => {
        console.log("deleted project ID: ", item);
      })
      .catch(error => {
        console.log(error);
      });
  });
}

function util() {
  getProjects()
    .then(() => {
      if (projectArray.length == 0) {
        reposExist = false;
      }
      if (projectArray.length < 20) {
        console.log("array is less than 20");
        reposExist = false;
      }
      deleteRepo(projectArray);
    })
    .catch(error => {
      console.log(error);
    });
}

// while (reposExist) {
//   util();
// }

1 个答案:

答案 0 :(得分:1)

while循环是同步的,而任何.then(或承诺await)中的所有内容都是异步的。初始线程永远不会终止。您的代码将简单地将getProjects的无限制调用排队,而只会console.log

简单的解决方案是弄清楚您要多久致电一次util(每秒一次?每5秒一次?),然后await一次Promise会在此金额后解决每次迭代的时间。

let reposExist = true;
function util() {
  console.log('running');
}

const resolveAfter5 = () => new Promise(res => setTimeout(res, 5000));
(async () => {
  while (reposExist) {
    util();
    await resolveAfter5();
  }
})();