Asynchronous looping · DSA

  • Crispin CIRHUZA
  • 12/12/2023
Rhinoceros Software Blog- Asynchronous looping · DSA

On NodeJS, we sometimes get confused when we have to loop over an array and execute asynchronous processes in order. Several options are proposed to us, the functions Array.map() and Array.reduce() for example but in this article I propose another approach which gives you more control in your code.

Below is our unique recursive function and takes care of looping over the items in order and with the total guarantee that the previous items have been processed correctly. We notice the absence of "catch" blocks, it is intended, indeed the processing that I perform does not give the possibility of error cases, just timeouts. In a real use case, consider adding these blocks.

Another added value of this recursive approach is that we have access to the previous item as well as the result of its processing, something that ordinary loops will offer with many mechanisms.


  const recursiveFunc = async ({ itemsTab, itemIndex = 0 }) => {
      // Fonction asynchrone personnalisée à remplacer par votre propre logique
      const processItem = async (item) => {
          // ... votre logique de traitement ici ...
          return new Promise(resolve => setTimeout(resolve, 1000)); // Exemple de délai
      };
  
      await processItem(itemsTab[itemIndex]);
  
      // Supprimer l'élément traité du tableau
      itemsTab.shift();
  
      // Si le tableau n'est pas vide, appeler récursivement la fonction
      if (itemsTab.length > 0) {
          await recursiveFunc({ itemsTab, itemIndex: itemIndex + 1 });
      } else {
          return { processingStatus: "ALL_PROCESSED" };
      }
  };
  
  // Exemple d'utilisation
  const OBJECT_ITEMS = Array.from(Array(100), (_, index) => index + 10);
  recursiveFunc({ itemsTab: OBJECT_ITEMS })
      .then(status => console.info("items processing status", status.processingStatus));
  
Conclusion

It is not enough that it works, it is worth inspecting data flows, optimizing algorithms to ensure a pleasant user experience. At Rhinoceros Software SAS, we pay particular attention to optimizing the programs that run in the applications that we deliver to you and thus guarantee you a better user experience.