简体   繁体   English

如何在异步/等待的无限while循环中捕获错误承诺?

[英]How to catch error promises in infinite while-loop with async/await?

I've faced the problem of catching errors in an infinite while-loop. 我已经遇到了在无限的while循环中捕获错误的问题。 So i want my code to exit node.js with proccess.exit(-1) if there's some errors cathed in the loop. 因此,如果循环中出现一些错误,我希望我的代码以proccess.exit(-1)退出node.js。 So here's the code: 所以这是代码:

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

Could u recommend please the best way to catch all errors in the loop? 您能否建议最好的方法来捕获循环中的所有错误?

You can wrap your block in a try catch : 您可以将块包装在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)
  }
}

Use this example: 使用此示例:

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

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM