Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling asynchronous events with jQuery

I have 3 asynchronous events which can only be run one after the other. When the first asynchronous event is completed, the second is run. When the second event is completed, the third is run. My code is as shown:

asynchronousEvent1(parameters1, function () { // Do stuff
    asynchronousEvent2(parameters2, function () { // Do stuff
        asynchronousEvent3(parameters3, function () { // Do stuff
        });
    });
});

This current format means that I need to have long sequences of functions nested within another. Is there some sort of an event handler I could use, for which the format of the code would be approximately:

asynchronousEvent1(parameters1, function () { /* Do stuff */ });
whenEvent1Completed(asynchronousEvent2(parameters2, function () { /* Do stuff */ });
whenEvent2Completed(asynchronousEvent3(parameters3, function () { /* Do stuff */ });
like image 427
Randomblue Avatar asked Jun 26 '26 07:06

Randomblue


1 Answers

You could use deferred objects introduced in jQuery 1.5. Assuming your functions return deferred objects, like the one returned by $.ajax (or of course you can create your own):

asynchronousEvent1(parameters1).pipe(function() {
    // do stuff
    return asynchronousEvent2(parameters2);
}).pipe(function() {
    // do stuff
    return asynchronousEvent3(parameters3);
}).then(function() {
    //do stuff
});

Have a look at the last example in deferred.pipe [docs].

like image 67
Felix Kling Avatar answered Jun 28 '26 22:06

Felix Kling