I read through various threads like this one for example.
But it really escapes me how to accomplish the following:
I have 4 functions, and want them happen one after another in sequence. Notice they are in incorrect order, to get my point across. I want the result that will output "1, 2, 3, 4'
function firstFunction(){
// some very time consuming asynchronous code...
console.log('1');
}
function thirdFunction(){
// definitely dont wanna do this until secondFunction is finished
console.log('3');
}
function secondFunction(){
// waits for firstFunction to be completed
console.log('2');
}
function fourthFunction(){
// last function, not executed until the other 3 are done.
console.log('4');
}
I tried to figure out callbacks but am getting lost :(
Isn't there some simple way to do this? Like looping through an array...
If I'm using callbacks, my working solution now looks like this:
I find that hideous. How am I supposed to keep track of this stuff if there is more than 2-3 sequences? Shudder...
I have played with the Promise, Sequence, Exception, Callback to understand how it works and finally made this code.
Call functions with callback and send result as parameter to another function in sequence and have a catch errors.
It's a great chance to start using jQuery Deferred.
Apart from the callbacks-based solution the code is readable, flexible and highly maintainable
http://jsfiddle.net/zerkms/zJhph/
PS: as an example of asynchronous code I've used
setTimeout
. The main thing is that in the end of the asynchronous part you need to calld.resolve()
to continue chaining methods.Further reading: http://joseoncode.com/2011/09/26/a-walkthrough-jquery-deferred-and-promise/
The idea is you'd do something like the following so that once the first function was done running, it'd know what to run as opposed to you having to figure it out on your own outside the function:
Also look up
.apply()
and.call()
.It's been a while and I noticed something about
deferreds
in jquery documentation, specifically thewhen
core API function.Code sample taken from http://jqapi.com/#p=jQuery.when