繁体   English   中英

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

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

我已经遇到了在无限的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);
    });
}

您能否建议最好的方法来捕获循环中的所有错误?

您可以将块包装在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)
  }
}

使用此示例:

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