Hi Guess Who,
I am no expert in JavaScript, so I urge others to can comment their views. I learned JavaScript by doing Chrome Extensions.
Imagine an API that you are using, that is all asynchronous. So lets say we have to call funcA, funcB, funcC, funcD in order. You can call each function under each other such as chaining calls:
function doProcess() {
// do something;
funcA(data, /*callback*/ function () {
// do something;
funcB(data, /* callback*/ function () {
// do something;
funcC(data, /* callback*/ function () {
// do something;
funcD(data, /* callback*/ function () {
// do something;
});
});
});
});
}
There is no problem with the above snippet, I use that all the time for Chrome Extensions, but one problem you see in that approach is that looks ugly when your process requires access to many asynchronous functions. To fix the uglyness, you can put them in methods, and then your code will be cleaner.
But what happens if the order of asynchronous calls are delicate? For example the same order as before calls, funcA, funcB, funcC, funcD, but the only difference is that if something in funcB occurs, it must do another thing like funcE, then after funcD, it can call either funcA or funcB. It will be a mess trying to do something like that above. Try doing it and you will understand the frustration.
One thing that comes to mind is state machines, if your logic requires access to multiple asynchronous calls, why not create a function queue? By using a function call queue, we can easily shift/unshift/push the next necessary call, and make the calls in right order cleanly:
var function_queue = [
funcA,
funcB,
funcC,
funcD
];
function doNextAction() {
if (function_queue.length) {
var next_function_call = function_queue.shift();
next_function_call();
}
}
function doProcess() {
// do something.
doNextAction();
}
function funcA() {
doNextAction();
}
function funcB() {
if (value is not null) {
doNextAction();
return;
}
// Result is null do something else.
function_queue.unshift(funcD);
}
function funcC() {
doNextAction();
}
function funcD() {
// Done
}
So it matters on your taste of programming, I used chaining for some chrome api stuff, but used function queues to manage Google Contacts which has a bunch of Asynchronous XHR calls. You can browse the source from here:
Hope that helped, if anyone else has some nice ideas regarding asynchronous programming, lets hear them :)
Kind regards,
Mohamed Mansour