我遇到了在无限的while循环中捕获错误的问题。因此,如果循环中出现一些错误,我希望我的代码以proccess.exit(-1)退出node.js。所以这是代码:
while (true) {
await promisifiedDelay(20000);
users.map(async (client) => {
//await client.login();
const allRequests = await client.getFollowRequests();
const requests = allRequests.slice(0, 100);
const currentName = await client.getCurUsername();
if (requests.length) {
console.log(`${currentName}: `, requests);
}
requests.map(async (request) => {
await promisifiedDelay(500);
await client.approve({ userId: request.node.id });
})
await updateAdded(requests.length, currentName);
});
}
您能推荐一种捕获循环中所有错误的最佳方法吗?
答案 0 :(得分:0)
您可以将代码块包装在try catch
中:
while (true) {
try {
await promisifiedDelay(20000);
users.map(async client => {
//await client.login();
const allRequests = await client.getFollowRequests();
const requests = allRequests.slice(0, 100);
const currentName = await client.getCurUsername();
if (requests.length) {
console.log(`${currentName}: `, requests);
}
requests.map(async request => {
await promisifiedDelay(500);
await client.approve({ userId: request.node.id });
});
await updateAdded(requests.length, currentName);
});
} catch (e) {
console.log(e);
break; // or process.exit(-1)
}
}
答案 1 :(得分:0)
使用此示例:
while (true) {
try {
await promisifiedDelay(20000).catch(err => throw err);
users.map(async (client) => {
//await client.login();
const allRequests = await client.getFollowRequests().catch(err => throw err);
const requests = allRequests.slice(0, 100);
const currentName = await client.getCurUsername().catch(err => throw err);
if (requests.length) {
console.log(`${currentName}: `, requests);
}
requests.map(async (request) => {
await promisifiedDelay(500).catch(err => throw err);
await client.approve({ userId: request.node.id }).catch(err => throw err);
})
await updateAdded(requests.length, currentName);
});
} catch(error) {
console.log(error);
}
}