allBlogsList

Using Recursion to Execute Asynchronous Calls

Introduction

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.

Implementation

We will need to create a Vue file for our dialog:

VueC1

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:

VueC2

Here is an example of the recursive call in our method:

VueC3

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.

VueC4

After we initialize our data, we also need to create a function to show the dialogs recursively.

VueC5

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.

Results

We call the dialog and then select OK and we see in the next photo that the call was successful.

Vue1

Vue2

In the next operation, we can see a new item has been set

Vue3

Eventually, we will reach the last item and after selecting the “OK” button, the modal/dialog will disappear.

Vue4