Success handling in custom javascript function Success handling in custom javascript function ajax ajax

Success handling in custom javascript function


How to use Deferreds:

function somethingAsynchronous() {    var deferred = new $.Deferred();    // now, delay the resolution of the deferred:    setTimeout(function() {        deferred.resolve('foobar');    }, 2000);    return deferred.promise();}somethingAsynchronous().then(function(result) {    // result is "foobar", as provided by deferred.resolve() in somethingAsynchronous()    alert('after somethingAsynchronous(): ' + result);});// or, you can also use $.when() to wait on multiple deferreds:$.when(somethingAsynchronous(), $.ajax({ something })).then(function() {    alert('after BOTH somethingAsynchronous() and $.ajax()');});

If your functions simply make an AJAX request, you can just return the actual promise returned by $.ajax():

function doAjax() {    return $.ajax({ /* ajax options */ });}doAjax().then(function() {    alert('after doAjax()');});


From what I can tell you really just want a better way to organize these callbacks. You should use a FIFO array or a queue. Your run all should do your stacking for you then execute the first function.

var RunQueue = function(queue){    this.init(queue);}var p = RunQueue.prototype = {};p.queue = null;p.init = function(queue){    this.queue = queue.slice(); //copy the array we will be changing it                                // if this is not practical, keep an index}p.run = function(){    if(this.queue && this.queue.length) {        var first = this.queue[0];        this.queue.shift();        var runQueue = this;        first(function(){ /*success callback parameter*/            runQueue.run();        });    }}

Usage:

var queue = [runFirst, runSecond, runThird, ...](new RunQueue(queue)).run();

If you really want to get fancy, and you may need to, you could pass in Objects in the array containing your parameters and have RunQueue append the last parameter as the success callback. You could even pass in the context to run the function in that object then call apply or call (whichever one uses the array) on your method.

{    method: runFirst,    context: someObject,    parameters: [param1, param2, param3];}


If Each of your function returns a state/function and then probably you could add a prototype to each state/function, then you would be able to call the functions like this, in fluent api way(method chaining).

runfirst().runSecond().runThird() 

and so on.

Lemme try to build a sample.

EDIT

See this, if it fits your design

EDIT 2I did not realise, you were talking about async method chaining. There is very good example here. It was discussed in this stackoverflow thread