我正在尝试将 while 循环与我的 util() 函数一起使用(它在代码底部被注释掉了)。当我尝试运行该程序时,我陷入了无限循环,我没有比控制台注销“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();
// }
最佳答案
while
循环是同步的,而 .then
(或 promise 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();
}
})();
关于javascript - while 循环的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51057231/