loading...

re: Handling a lot of requests in JavaScript with promises VIEW POST

TOP OF THREAD FULL DISCUSSION
re: Thanks for the article. I was looking for an article which can handle huge number of api calls to maps.google.com autocomplete api, I am glad that ...
 

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
code of conduct - report abuse