Home > OS >  I want to execute 4 api's parallelly from my javascript to display data in each tab, but specif
I want to execute 4 api's parallelly from my javascript to display data in each tab, but specif

Time:03-24

I have 4 tabs in html and i have to call 4 diff api's which return json and render that output in each tab.

enter image description here

Now the problem is, when i write ajax staments one after another with async:false, the page loads and it takes time as it callls all 4 api's one after another.

I want the data on first tab "dashboard" to load first as it comes up quickly. Meanwhile the other tabs are loading.

$.ajax({
    url : base_url "es/kernelStats",
    type : "get",
    async : false,
    dataType: 'json',
    success : function(data) {    
    console.log("ES Data ",Object.values(data));
    drawDataTable(data,"es");
    }
});

$.ajax({
    url : base_url "tab1/stats",
    type : "get",
    async : false,
    dataType: 'json',
    success : function(data) {
        console.log(" Data ",data);
        drawDataTable(data,"tab1");

    }
});


$.ajax({
    url : base_url "tab2/Stats",
    type : "get",
    async : false,
    success : function(data) {
        console.log("Data ",data);
        drawDataTable(data,"tab2");
    }
});

$.ajax({
    url : base_url "tab3/Stats",
    type : "get",
    async : false,
    success : function(data) {
        console.log("Data ",data);
        drawDataTable(data,"tab3");
    }
});

$.ajax({
    url : base_url "tab4/Stats",
    type : "get",
    async : false,
    success : function(data) {
        console.log("Data ",data);
        drawPatchingDataTable(data,"tab4");
    }

The problem is, each api takes 3-4 sec to get data and when executed sequentially it takes 12-15seconds which is not desirable.

When i change async : true, in all above, then the json outputs that gives some numeric values changes and the data is not reliable.

I have also tried this using fetch api, (used fetch statements / promise.all ) but all these give wrong response.

CodePudding user response:

Promise.all is the method to use. You should give that another go

CodePudding user response:

Note: that time will take that much only, but you can try this method may be this work or you can make some changes in that,

const fireApi = (url, param, afterSuccess) => {
    $.ajax({
        url : base_url url,
        type : "get",
        success : function(data) {
            console.log("Data ",data);
            afterSuccess(data, param)
        }
    });
}
fireApi("tab1/stats", "tab1", drawDataTable)
fireApi("tab2/stats", "tab2", drawDataTable)
fireApi("tab3/stats", "tab3", drawDataTable)
fireApi("tab4/stats", "tab4", drawPatchingDataTable)
  • Related