admin管理员组

文章数量:1402449

I want to make some wine. And my function does:

function wine(){
    growGrapes();
    process(grapes);
    makeWine();
    bottle();
}

However, Since my functions often consist of $.ajax() request, some other functions get carried out first. I have used the success tool, but it helps for one ajax request only.

success:function(result){
    //Some Code         
}

What I actually want is a sequence. Literally, grapes get processed before growing them. What is a easiest approach?

I want to make some wine. And my function does:

function wine(){
    growGrapes();
    process(grapes);
    makeWine();
    bottle();
}

However, Since my functions often consist of $.ajax() request, some other functions get carried out first. I have used the success tool, but it helps for one ajax request only.

success:function(result){
    //Some Code         
}

What I actually want is a sequence. Literally, grapes get processed before growing them. What is a easiest approach?

Share Improve this question asked Jul 17, 2014 at 14:36 X PahadiX Pahadi 7,4735 gold badges56 silver badges83 bronze badges 4
  • 3 jQuery Promises are the way to go. It supports running multiple tasks in parallel or series using $.when(PassArrayOfPromises) and promise.then() etc – iCollect.it Ltd Commented Jul 17, 2014 at 14:37
  • 3 @TrueBlueAussie ,put your ment as answer. – Jashwant Commented Jul 17, 2014 at 14:44
  • @Jashwant: Have posted it, but no time to put up a practical example (which I usually like to do) – iCollect.it Ltd Commented Jul 17, 2014 at 14:47
  • See stackoverflow./q/16384841/218196 – Felix Kling Commented Jul 17, 2014 at 14:56
Add a ment  | 

6 Answers 6

Reset to default 4

jQuery Deferred Objects & Promises are the way to go. http://api.jquery./category/deferred-object/

They supports running multiple tasks in parallel or series using $.when(PassArrayOfPromisesToRunInParallel) to run processes in parallel and promise.then() to run items sequentially.

Call the next function in the success handler of the $.ajax call of the previous function!

Example:

function growGrapes(){
  // lines of code
  $.ajax({
    success: function(result){
      // call next function here - process(grapes); and so on...
    }   
  });   
}

The above makes sure the functions get called sequentially after the other..

You can make your Ajax calls synchronous (in sequence) by ensuring you have async: false in your $.ajax() settings.

For example:

$.ajax({ url: 'url', 
         async: false,
         dataType: 'json',
         success: function(data) {

         }
});

First solution :

Make your ajax call syncronous by setting async : false when setting up your ajax call

$.ajax
({
   async : false,
   /* other settings */
});

Warning: This solution causes the UI to hand on intensive processing. This should never be used when doing anything rigorous on the server. My remendation for using this is to only use it in checking flags or loading simple data.

Second solution :

As stated in the ments, use jQuery promises to set up the ordering. Here is a tutorial

I'll try to e back and provide a code example for this solution soon

Third solution :

Make your next call the success handler, or call the next step from the success handler

$.ajax
({
   success : NextStep,
   /* other settings */
})

One solution is to use queue() function. This way you can execute as many functions as you want

    var ajaxQueue = $({});


    $.ajaxQueue =  function(ajaxOpts) {  

        // queue the method. a second call wont execute until this dequeues
        ajaxQueue.queue(function(next) {
            // for this example I serialize params, but you can save them in several variables 
            // and concat into ajaxOpts.data
            var params = method_that_get_params_and_serialize_them();
            ajaxOpts.data = params;      

            ajaxOpts.plete = function() {       
                next();
            };

            $.ajax(ajaxOpts);
        });
    };

then your functions should be like this:

    function growGrapes(){
        $.ajaxQueue({
            cache: false,
            type: "POST",
            url: "someUrl",
            dataType: "json",
            data: "", // we fill data inside  ajaxQueue() method
            success: function( response) {                      
                //do things with response

            } 
        });
    }

If you want to keep it tidy and clean to let people see how your calls are made, you can simply pass a callback function to another like this:

function growGrapes(callback) {
  $.ajax({
  ...
    success: function (){
      // Something
      if (typeof callback === typeof Function) callback();
    },
  ...
  });
} 

function wine(){
  growGrapes(function (){
    process(grapes);
  });
}

本文标签: Carry out JavascriptjQuery functions in a sequenceStack Overflow