Associate Sitecore Developer
Using Recursion to Execute Asynchronous Calls
I have worked with business analysts where some of their requirements require changing certain features of an Single Page Application (SPA) with Vue.js. It could be for modifying a function for handling a list of items, rendering new components such as modals or dialogs, or fixing bugs. However, I recently came across a challenge where our SPA has a list of selected items and each item asks the user if they want to confirm continuing the execution, if confirmed, an asynchronous call is called. A common solution to handling multiple asynchronous calls is to use the reduce method. At first, I thought this method would solve the issue, however, the issue is that we are calling each dialog within the loop. To resolve this specific we can use recursion.
We will need to create a Vue file for our dialog:
We will also need a function to return a Promise, we can create a mock service file called mock-service.js and initialize it like this:
Here is an example of the recursive call in our method:
In this method, we will need to test if the list is empty. If the list is not empty, then we can continue executing the recursion and call the dialogs. In our action method, when the user selects “OK” we can call the API and once the API is done loading, we can shift the item from the list and continue until we reach the last item.
We will also need to initialize some data for our example.
After we initialize our data, we also need to create a function to show the dialogs recursively.
In this function, we call the dialog and if our selection is confirmed, we call the API method executeRecursiveMethod(). If the results are successful, then we call another dialog to say that the call was successful. And when we execute the action again, we use the shift method to remove the first item in the list and call the recursive method again.
We call the dialog and then select OK and we see in the next photo that the call was successful.
In the next operation, we can see a new item has been set
Eventually, we will reach the last item and after selecting the “OK” button, the modal/dialog will disappear.