简体   繁体   中英

Carry out Javascript/jQuery functions in a sequence

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?

jQuery Deferred Objects & Promises are the way to go. http://api.jquery.com/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..

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 recommendation for using this is to only use it in checking flags or loading simple data.

Second solution :

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

I'll try to come 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 */
})

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) {

         }
});

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.complete = 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);
  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM