Execute Javascript / jQuery Functions in Sequence

I want to make some wine. And my function:

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

However, since my functions often consist of a query $.ajax(), some other functions are executed first. I used the success tool, but it only helps with one ajax request.

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

What I really want is a sequence. Literally, grapes are processed before they are grown. What is the easiest approach?

+4
source share
6 answers

Call the next function in the successcall handler of the $.ajaxprevious function!

Example:

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

The above ensures that functions are called sequentially after another.

+3
source

jQuery Promises - . http://api.jquery.com/category/deferred-object/

, $.when(PassArrayOfPromisesToRunInParallel) promise.then() .

+4

:

ajax- , async: false ajax-

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

. . - . , .

:

, jQuery promises, .

:

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

Ajax- (), , async: false $.ajax().

:

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

         }
});
+1

queue(). ,

    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);
        });
    };

:

    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

            } 
        });
    }
0

, , , :

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

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

All Articles