DEV Community


Discussion on: Handling a lot of requests in JavaScript with promises

srikanthsm profile image
Srikanth-SM • Edited

Thanks for the article. I was looking for an article which can handle huge number of api calls to autocomplete api, I am glad that I found this article, very well written with step by step performance optimisation.

But even though I am using the above pattern I am getting getaddrinfo enotfound error. I am making a huge number of api calls to api.
So can you suggest me a way in the above pattern to make a retry request for the failed requests?
Also is there a github repo for the above code?

karataev profile image
Eugene Karataev Author

Great question!
Handling errors heavily depends on your particular use case. At least I can think of three ways:

  • just skip the rejected promise and move on
  • have a predefined amount of attempts before move on
  • keep trying to fetch a request until success

Here's the simplified example for the 3rd option. I use series helper for simplicity. Fake API request may fail. We keep trying to request API until success.

function fetchApi(id) {
  const ms = 200 + Math.round(Math.random() * 500);
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      Math.random() > 0.5 ? resolve() : reject();
    }, ms);

async function fetchAndLog(id) {
  let success = false;
  do {
    try {
      await fetchApi(id);
      console.log(`${id} success`);
      success = true;
    } catch (e) {
      console.log(`${id} fail`);
  } while (!success);

series(getIdList(5), fetchAndLog)
  .then(() => {
    console.log('all done');

And the result is

1 fail
1 fail
1 success
2 fail
2 success
3 success
4 fail
4 success
5 success
all done