-1

I am creating a Node.js module that takes a list of movie titles and fetches their respective metadata from omdbapi.com.

These lists are often very large and sometimes (with my current slow internet connection) the connection stalls due to too many concurrent connections. So I set up a timeout/abort method that restarts the process after 30 seconds.

The problem I'm having is that whenever I lose internet connection or the connection stalls, it just bails out of the process, and doesn't restart the connection.

Example:

async function getMetadata () {
  const remainingMovies = await getRemainingMovies();

  for (let i = 0; i < remainingMovies.length;i++) {
    const { data, didTimeout } = await fetchMetadata(remainingMovies[i]);

    // Update "remainingMovies" Array...

    if (didTimeout) {
      getMetadata();
      break;
    }
  }

  if (!didTimeout) {
    return data;
  }
}

This is obviously a simplified version but essentially:

  • The getMetadata Function gets the remainingMovies Array from the global scope.
  • Fetches the metadata from the server with the fetchMetadata Function.
  • Checks if the connection timed out or not.
  • If it did it should restart the Function and attempt to connect again.
  • If it didn't timeout then finish the for loop and continue.
rootr
  • 382
  • 1
  • 11
  • You may want to use `try/catch` for fetching and handle error scenario in catch as using `await` your code will wait on that line (rest of the function do not get executed) until things get returned from server else it will error out for which you dont have handler. – Rikin Nov 30 '18 at 21:43

1 Answers1

0

I guess you want something similar to below script. Error handling using try/catch for async/await which probably is what you are looking for as a missing puzzle.

async function getMetadata() {
  const remainingMovies = await getRemainingMovies();

  remainingMovies.map(movie => {
    try {
      return await fetchMetadata(movie);
    } catch (err) {
      return getMetadata();
    }
  });

}
Rikin
  • 5,351
  • 2
  • 15
  • 22
  • I didn't even think about using `Array.map()` in this situation. So `fetchMetadata` returns an `Object` and if it throws an error, it will catch it and re-run the `getMetadata` Function. I think this **IS** what I was looking for. – rootr Nov 30 '18 at 22:24