1

I have two web services calls I need to make from my JQuery 1.9.1 app. I need the results from the first one before I make the second call.

It appears that my getJSON requests do not block the thread. I'm told that javascript is not multi-threaded, so how do I block between these server calls?

Thom
  • 14,013
  • 25
  • 105
  • 185
  • 12
    Don't. Put the second call in the first call's callback function. – Barmar Jul 16 '13 at 11:10
  • Be aware, that the browser will block as well, if you block the JavaScript thread (unless using workers, e.g.)! – Sirko Jul 16 '13 at 11:11
  • Or, even better (if possible) create a server proxy that combines the calls and then call this proxy. Then you're making the one trip rather than two. – Chris Dixon Jul 16 '13 at 11:13
  • 1
    Since JavaScript is **not** multithreaded, you can't block the *single* thread without blocking your whole app! – Bergi Jul 16 '13 at 11:17
  • @Bergi - He isn't talking about threads, he's talking about asynchronous requests to the server. each of which will execute some code upon completion, thus fully allowing a race condition in JS. In that sense, they act very much like threads. – Steven Moseley Jul 16 '13 at 11:26

3 Answers3

3

jQuery's ajax functions all return a jqXHR object that implement the Promise interface.

Instead of blocking an asynchronous request (and everything else), nest your requests like so

$.ajax({...})
    .done(function( data ) {
        // second request
        $.ajax({...});
    });
André Dion
  • 21,269
  • 7
  • 56
  • 60
2

Well, you don't need to block threads, that's old school.

You have two options:

  • Make the ajax call syncronous.
  • Cascade the ajax calls, so the second is made only once the first one is completed.

I recommend the second approach, because that is the right way to do it.

/* Call 1 */
$.ajax({
    url: 'first url to call',
    data: 'first data sent to the server',
    success: function (results1){

        // Do something with the results    

        /* make the second call */
        $.ajax({
            url: 'sencond url to call'
            data: 'second data sent to the server'
            success: function(results2){

                // Do something when all completed
            }                
        });
    }
});
Adrian Salazar
  • 5,279
  • 34
  • 51
1

Call your 1st ajax request in async false mode to server

$.ajax({
url: Url,
dataType: 'json',
async: false,
 data: myData,
 success: function(data) {
  //stuff
  }
});