Live data from Hacker News

Multiple Simultaneous Ajax Requests (with one callback) in jQuery

css-tricks.com

1–10 of 31 posts

Re: Multiple Simultaneous Ajax Requests (with one callback) in jQuery

#4
globalStore? Ewwwww. As the jQuery documentation states on $.when [1], the .then() callback function will be called with a number of arguments equal to those passed to $.when(), ergo in this example:

.then(function(html, css, feature) {});

Which avoids the need for a global / shared object. If you need access to these resources outside of this one callback, prefer to pass the promise object itself around; promises allow multiple 'then's to be added, either before or after the promise resolves.

I'm working on a blog post about promises and related patterns (in the context / implementation of Angular, but they're equally valid for jQuery or other promise implementations), I'll post it on HN hopefully somewhere this weekend or early next week.

[1] https://api.jquery.com/jQuery.when/

Re: Multiple Simultaneous Ajax Requests (with one callback) in jQuery

#6
post #5

This is the proper solution: http://css-tricks.com/multiple-simultaneous-ajax-requests-on...

   $.when(
     // Get the css-tricks once
     $.get("http://css-tricks.com"),

     // get it twice
     $.get("http://css-tricks.com")
    ).then(function( csstricks1, csstricks2 ) {
      
      console.log( 'Fetched css tricks' );
  
      console.log( csstricks1, csstricks2 );
    });
csstricks1[0] is the content object and usually what you'll want - for example, if the response is json.

Re: Multiple Simultaneous Ajax Requests (with one callback) in jQuery

#8
Yes, promises are great. It would be nice to have a function on a promise that returns a regular callback which you can pass to functions that only know about callbacks.

Also, if you are using promises for getter functions, you'll have to store those promises somewhere, so that next time you don't load them again. Basically "getting" a resource involves caching, promises, and maybe even throttling. So its ideal implementation is not really just a promise.

Check this out: http://platform.qbix.com/guide/patterns

Re: Multiple Simultaneous Ajax Requests (with one callback) in jQuery

#10
Or you can make a count-down latch of some kind:

  var num_results = 3;
  var results = []
  var makeCallback = function(index) {
    return function(response) {
      num_results -= 1;
      results[index] = response;
      if (num_results > 0) {
        return;
      }
      
      // actually do stuff here, all results are loaded.
    };
  };
  $.get("/a", makeCallback(0));
  $.get("/b", makeCallback(1));
  $.get("/c", makeCallback(2));
  // etc
It's also not hard to make a generic latch-producing function so you can just write stuff like:

  var l = makeLatch(callback);
  $.get("/a", l());
  $.get("/b", l());
  $.get("/c", l());
Post reply on HN