سؤال

I have a problem which am trying to find a solution. On the Front End am trying to display data for the user to compare in a HTML table. There are three data sources from which am fetching my data using Ajax requests.

Data source 1: time taken ~8 seconds Data source 2: time taken ~8 seconds Data source 3: time taken ~30 seconds

My Approach- The Ajax calls are made in a function as shown below:-

   function fetchAjax(){
         aggregatedAjaxObj = {}

         ajax.request1(){

    }
       ajax.request2(){

    }
       ajax.request3(){

    }

 //Add all the response in the  aggregatedAjaxObj Object.

}

function render(){

// render the object in the html table & display after a interval of 30 sec
}

Am using Node.js, Backbone js & Jquery.

If there is any better approach would love to try it out.

هل كانت مفيدة؟

المحلول

You have a race condition here as well as introducing a 30 second delay. Also, you have global state.

Both of these are really unreliable and bad.

Assuming you don't want to introduce a good promises library (I'd recommend bluebird) using the tools you already have it can be done with:

Using jQuery:

var request1 = $.ajax(...);
var request2 = $.ajax(...);
var request3 = $.ajax(...);
$.when(request1,request2,request3).done(function(results){
    // results contains all 3 request data
    // no delay, will resolve when all 3 are done
    // requests are made simultaneously
    render(results);
});

Using standard Promise (Bluebird compatible):

var request1 = $.ajax(...);
var request2 = $.ajax(...);
var request3 = $.ajax(...);
Promise.all(request1,request2,request3).then(function(results){
    // results contains all 3 request data
    // no delay, will resolve when all 3 are done
    // requests are made simultaneously
    render(results);
});

The lambda can always be away with, you can do:

Promise.map(["url1","url2","url3"],$.get).all(render);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top