-1

I need the application to wait till the first request is completed. The scenario is,

if (str != "") {
  if (str.match(",")) {
        var poolSequencedStatus = $.get("Request1.do"), function(response){
             //alert("Req1")
        }
  }

  $.get("Request2.do"), function(response){
     //alert("Req2")
  }
}

The Request2 should be called only after completing Request1 if the string contains the character ','.

Nims
  • 41
  • 1
  • 6

4 Answers4

0

You can take advantage of promises and wrap it in a $.when($.get("Request1.do")).then(function(){});

http://api.jquery.com/jquery.when/

TGH
  • 38,769
  • 12
  • 102
  • 135
0

Create a function of second request :

function GetRequest()
{

 $.get("Request2.do"), function(response){
     //alert("Req2")
  }

}

and call in the success of first:

if (str != "") {
  if (str.match(",")) {
        var poolSequencedStatus = $.get("Request1.do"), function(response){
             GetRequest();
        }
  }
Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
  • If you want cleaner code, at least you could then get rid of the anonymous function wrapper and do `$.get( "Request1.do", GetRequest );` – JJJ May 26 '14 at 05:52
0
if (str != "") {
  if (str.match(",")) {
        var poolSequencedStatus = $.get("Request1.do"), function(response){
             //alert("Req1");
           $.get("Request2.do"), function(response){
     //alert("Req2")
           }
        }
  }


}
guest271314
  • 1
  • 15
  • 104
  • 177
0

By default Jquery works on sync mode.

Check the value of async:false of your $.ajax settings.

Otherwise, you can use the benefit of $.when() in your latest jQuery.

    // Using the $.when() method, we can create an object that behaves similarly
// to Deferred objects, but for COMBINATIONS of Deferred objects.
//
// The $.when() method creates a Deferred object that is resolved or rejected
// when all the Deferred objects passed into it are resolved or rejected.
var getPromise = function(name) {
  var dfd = $.Deferred();
  var num = Math.floor(Math.random() * 1000);
  setTimeout(function() { dfd.resolve(name + ": " + num); }, num);
  return dfd.promise();
};

var list = $("<ul/>").appendTo($("#target").empty());
var printLine = function(str) {
  $("<li class=well/>").html(str).appendTo(list);
};

// Each of these Promises will individually print when resolved.
var promiseA = getPromise("A").done(printLine);
var promiseB = getPromise("B").done(printLine);
var promiseC = getPromise("C").done(printLine);

// And this code will execute once all Promises have resolved.
$.when(promiseA, promiseB, promiseC).then(function(numA, numB, numC) {
  printLine(numA + ", " + numB + ", " + numC);
});
codebased
  • 6,945
  • 9
  • 50
  • 84