Как отловить обещания ошибок в бесконечном цикле while с помощью async / await? - PullRequest
0 голосов
/ 05 декабря 2018

Я столкнулся с проблемой перехвата ошибок в бесконечном цикле while.Поэтому я хочу, чтобы мой код выходил из node.js с помощью proccess.exit (-1), если в цикле есть ошибки.Итак, вот код:

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

Не могли бы вы порекомендовать, пожалуйста, лучший способ отловить все ошибки в цикле?

Ответы [ 2 ]

0 голосов
/ 05 декабря 2018

Используйте этот пример:

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

}

0 голосов
/ 05 декабря 2018

Вы можете обернуть свой блок в 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)
  }
}
...