What is the best way to handle multiple asynchronous calls?

I am dealing with multiple asynchronous calls, specifically four of them.

this.lazyLoadData();
this.lazyLoadData();
this.lazyLoadData();
this.lazyLoadData();

The issue arises because each HTTP request may take a different amount of time. Additionally, I am sending different query parameters for fetching paginated data from the backend in each request.

As a result, the first this.lazyLoadData may sometimes finish later than the second one, depending on the response times from the backend.

To address this problem, I attempted to implement the use of async and await:

await this.lazyLoadData();
await this.lazyLoadData();
await this.lazyLoadData();
await this.lazyLoadData();

async lazyLoadData(cb?) {
  const filtersParam: any = {
        page: this.filterService.dashboardPage,
        size: 25,
      }

      let response = await this.processMonitorService.monitoring(filtersParam);
      response.then(data => {
         console.log('made http call');
      });
      ...
}

However, even with async and await, the four HTTP calls still do not occur in order as expected.

When calling lazyLoadData four times in the span of one second and awaiting each result, the responses do not come back in the correct sequence. Sometimes, the third request is executed before the second, and so on.

How can I resolve this issue?

Answer №1

Is there a specific reason why they must be in a particular order? Maybe you could gather the necessary parameters beforehand and then use the results sequentially.

Although you could have them wait, it might negatively impact performance:

this.lazyLoadData().then(() => this.lazyLoadData())

and so on.

A more efficient approach would be to not rely on the current state but instead receive the parameters externally. For example:

await this.lazyLoadData(1);
await this.lazyLoadData(2);
await this.lazyLoadData(3);
await this.lazyLoadData(4);

Where the parameter represents the page number.

Also, what is the overall purpose of making 4 requests? Could you simply request a larger page size (e.g., 100) if all 4 pages are needed simultaneously?

Answer №2

If you want to optimize this process, I recommend utilizing the Promise.all() method.

Transform your code into something like the following:

    const promisesArray = [
        this.fetchData(1),
        this.fetchData(2),
        this.fetchData(3),
        this.fetchData(4),
    ]

    Promise.all(promisesArray).then((results) => {
        console.log(results) // this will display the results of all 4 requests in sequence
    })

Furthermore, consider refactoring a portion of your code for better efficiency.

The fetchData function can be transformed as shown below:

    async fetchData(parameter ? ) {
        const requestParams: any = {
            page: this.filterService.dashboardPage,
            size: 25,
        }

        return this.dataService.getData(requestParams);
    }

Answer №3

Make sure your code is wrapped within an asynchronous function:

(async()=>{
  await this.loadDataWithDelay();
  await this.loadDataWithDelay();
  await this.loadDataWithDelay();
  await this.loadDataWithDelay();
}());

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

:Incorporating active hyperlinks through javascript

Hey there, I've encountered a little conundrum. I have a header.php file that contains all the header information - navigation and logo. It's super convenient because I can include this file on all my pages where needed, making editing a breeze. ...

What is the most efficient way to retrieve a value (specifically an access token) within a function without using

const callback = (req, res) => { // Your application requests refresh and access tokens after verifying the state parameter if (state === null || state !== storedState) { ... } else { res.clearCookie(stateKey); var authOptions = {...} ...

Displaying JSON data in React components can be done by using the `map` method

Within another file, I have obtained JSON data structured as follows: { "feed": [ { "id": 1, "text": "Seeking advice on meditation, when do you all practice?", "messages" ...

Leverage JavaScript to retrieve the formatting of an element from an external CSS stylesheet

Check out this HTML snippet: <html> <head> <link rel="stylesheet" type="text/css" media="all" href="style.css"> </head> <body> <div id="test">Testing</div> <script> ...

Changing the default date display in Vue.js

Is there a way to automatically set today's date as the default date on the datepicker? Here is the code snippet: <template lang="html"> <input type="date" v-model="date"> </template> <script lang="js"> export default { nam ...

Determining Field of View (FOV) for a perspective camera in ThreeJS following a browser window resize

After changing the size of the browser window, I'm trying to determine the correct Three.JS camera FOV. I have looked at several related questions, but haven't found a solution yet: How to calculate fov for the Perspective camera in three js? C ...

Angular controller unable to detect CordovaNetwork

I'm experiencing some issues with the CordovaNetwork plugin in an IONIC v1.x application. After installing it using the command: sudo cordova plugin add cordova-plugin-network-information I injected the plugin into an angular controller like this: ...

Using Placeholder in JavaScript for Multiple Form Validations

I am currently facing an issue with my form validation. It checks each input to determine if it is valid or not, but the problem arises when only one input is valid, as all inputs are then considered valid. I have tried moving the return true statement, bu ...

I have a professional sales page showcasing data from a JSON file. My goal is to efficiently transfer details for a single listing to a separate results page

My main PHP file, index.php, successfully displays listings from a JSON file. However, I am having trouble sending the details of a single listing from this page to another page (result.php). How can I showcase the details of this individual listing on the ...

Steps to releasing JavaScript and asset files on npm

I have created a custom UI component for internal company use and released it on npm. However, after installing the package, I noticed that only the index.js file is showing up in the node_modules directory. I am not utilizing any package builders or ES m ...

Preserving DOM object reference in ASP.Net Ajax PageMethod

When invoking an ASP.Net PageMethod, the call is made like this: function doSomething(htmlElement) { PageMethods.GetText(onSuccess, onFailure); } Is there a recommended approach to keep a reference to the htmlElement in the scenario above, allow ...

Getting the most out of setInterval() - a guide in jQuery

I am currently working on an auto slide feature and could use some guidance with setInterval(). From my understanding, setInterval() is used to repeat functions infinitely, which is exactly what I need for this project. Here is the current layout: HTML & ...

Utilizing JavaScript within Razor templates

Is there a way to achieve something like this: <input type="text" id="ZIP" name="ZIP" /> <a <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ed859f888bd0adb89f81c3ac8e99848283">[email protected]</a>("Verif ...

Incorporating commas as a number is typed by the user, such as 1,000, 10,000, 100,000, 1,000,000, 10,000,000,

As a beginner, I researched and managed to develop this code successfully. One issue I'm facing is that when users input numbers, there are no commas separating the thousands or millions. Does anyone have suggestions on how to automatically add commas ...

jQuery does not seem to be able to recognize the plus sign (+)

I am currently developing a calculator program and facing some challenges with the addition function. While the other functions ("/", "-", "*") are working fine, the plus ("+") operation seems to be malfunctioning. Here's the snippet of HTML and JavaS ...

Running nodemon and parcel watch simultaneously can be achieved by combining them in a single command

Is it possible to combine the nodemon and watch:js scripts into one command for easier execution? I have tried other solutions without success... // package.json "scripts": { "start": "nodemon server.js", "watc ...

No matter how hard I try, I can't seem to retrieve any data from the gremlin-server in my node/express application. The promise remains forever pending

As you continue reading, I have a question related to Node/Express or Gremlin - but I'm not sure which one is causing the issue. On my Linux machine as SU, I've initiated Janusgraph using the following command in Docker: docker run --name janusg ...

I am interested in obtaining every separate return value from the reduce() function instead of just the final total

initialValue currentValue position elements final value first calculation 0 1 1 [0, 1, 2, 3, 4] 1 second run 1 2 2 [0, 1, 2, 3, 4] 3 third round 3 3 ...

Improve the looping mechanism to efficiently extract key values from an object and store them in an array

I am working with an object that contains various questions, each with a different difficulty level indicated by the "difficulty" property. I have implemented a for loop to sort the questions into categories based on their relative difficulty, such as easy ...

Is this jQuery script correct?

function like(){ $('#likeo').html('<div style = "align:center"><img src = "images/loader.gif"></div></br>').show(); var pid = <?php echo $post; ?>; $.post('include/like.php',{pids:pid} ...