how to avoid callback chains? - javascript

I need a bunch of functions to be called in strict order. It's also very important that the next function waits until the previous one has finished.
Right now I'm using chained callbacks:
callMe1(function(){
callMe2(function(){
callMe3(function(){
callMeFinal();
});
});
});
This works but seems to be a little ugly.
Any suggestions for a different approach?

If you use jQuery, then you can use queue to chain the functions.
$(document)
.queue(callMe1)
.queue(callMe2);
where callMeX should be of form:
function callMeX(next) {
// do stuff
next();
}

You can implement a "stack" system:
var calls = [];
function executeNext(next) {
if(calls.length == 0) return;
var fnc = calls.pop();
fnc();
if(next) {
executeNext(true);
}
}
/*To call method chain synchronously*/
calls.push(callMe3);
calls.push(callMe2);
calls.push(callMe1);
executeNext(true);
/*To call method chain asynchronously*/
calls.push(callMe3);
calls.push(function(){
callMe2();
executeNext(false);
});
calls.push(function(){
callMe1();
executeNext(false);
});

Not sure if this would help you, but there is a great article on using deferreds in jQuery 1.5. It might clean up your chain a bit...
Also, my answer on Can somebody explain jQuery queue to me has some examples of using a queue for ensuring sequential calls.

You might want to pass parameters to the functions, I do not believe you can at the time of this writing. However...
function callMe1(next) {
console.log(this.x);
console.log("arguments=");
console.log(arguments);
console.log("/funct 1");
this.x++;
next();
}
function callMe2(next) {
console.log(this.x);
console.log("arguments=");
console.log(arguments);
console.log("/funct 2");
this.x++;
next();
}
function callMe3(next) {
console.log(this.x);
console.log("arguments=");
console.log(arguments);
console.log("/funct 3");
this.x++;
next();
}
var someObject = ({x:1});
$(someObject).queue(callMe1).queue(callMe2).queue(callMe3);

Wrapping your functions, arguments intact, with an anonymous function that plays along with .queue works too.
Passing Arguments in Jquery.Queue()
var logger = function(str, callback){
console.log(str);
//anything can go in here, but here's a timer to demonstrate async
window.setTimeout(callback,1000)
}
$(document)
.queue(function(next){logger("Hi",next);})
.queue(function(next){logger("there,",next);})
.queue(function(next){logger("home",next);})
.queue(function(next){logger("planet!",next);});
Example on JSFiddle: http://jsfiddle.net/rS4y4/

Related

How to wait for callback while iterating an array

I am working with a transnational framework within Javascript. So I need to wait for the previous query to finish before I move on. For example...
// Explicit this won't work because the length is not static
var i = [1,2,3]
doSomething(i[0], function(){
doSomething(i[1], function(){
doSomething(i[2], function(){
commitTransaction()
}
})
})
From this example I can't figure out a way to do this dynamically. It feels like a queue/recursion problem but I can't seem to crack it.
Does anyone else have an idea? I can also wrap in promises so that is an option as well, although that seems less synchronous.
Use async.eachSeries. So your code would translate to:
var transaction = {...};
async.eachSeries([1, 2, 3], function(value, callback) {
doSomething(value, transaction, callback);
}, function(err) {
if(err) throw err; // if there is any error in doSomething
commitTransaction(transaction);
});
jsFiddle Demo
I would suggest making a queue to do this. It would take the array, the generic callback function and a final function to callback with. Basically, the best way to accomplish this is to allow your functions to expect to have values injected.
The core assumption is that it is understood the caller will allow their callback function to have the current value and next callback function injected. That basically means we will end up with a function I have named queueAll which looks like this
function queueAll(arr,cbIteration,final){
var queue = [function(){ cbIteration(arr[arr.length-1],final) }];
for(var i = arr.length-2; i > 0; i--){
(function(next,i){
queue.unshift(function(){ cbIteration(arr[i],next) });
})(queue[0],i)
}
cbIteration(arr[0],queue[0]);
}
It takes the final call, places it in the queue, and then iterates, placing subsequent callback functions in the queue with the current value closed over, as well as closing over the front of the queue which at that point is the next call back. It is fairly simple to use. Pass it an array, a callback which expects values to be injected, and a final function.
In your case it would look like
queueAll(i,function(item,next){
doSomething(item,next);
},function(){
commitTransaction();
});
Stack Snippet Demo
//## <helper queue>
function queueAll(arr,cbIteration,final){
var queue = [function(){ cbIteration(arr[arr.length-1],final) }];
for(var i = arr.length-2; i > 0; i--){
(function(next,i){
queue.unshift(function(){ cbIteration(arr[i],next) });
})(queue[0],i)
}
cbIteration(arr[0],queue[0]);
}
//## </helper queue>
//## <user defined functions>
function doSomething(val,callback){
setTimeout(function(){
console.log(val);
callback();
},val*10);
}
function commitTransaction(){
console.log("commit");
}
//## </user defined functions>
//## <actual use>
var arr = [10,20,30];
queueAll(arr,function(item,next){
doSomething(item,next);
},function(){
commitTransaction();
});
//## </actual use>
Actually, I think promises are exactly what you're looking for. But for a traditional callback approach, consider the following:
var state = false,
doSomething = function (value, callback) {
/* do stuff with value */
if (!state)
doSomething(newValue, callback);
else
callback();
};

wait for function done (with setInterval) and run next function

how to run next function after first done with setInterval?
for example:
step1();
step2();
setInterval(step1, 1000).done(function() {
setInterval(step2, 1000).done( /* next step */);
});
please help me with solution!
Edit: This is an old answer. Now you can achieve this using promises also but the code will be slightly different.
If you don't want to use a promise you can use a simple flag to achieve such a thing. Please see example below:
var flag = true;
function step1() {
console.log('title');
}
function step2() {
console.log('subtitle');
}
function wrapper() {
if(flag) {
step1();
} else {
step2();
}
flag = !flag;
}
setInterval(wrapper, 30000);
If you want to chain functions on completion you can use callback functions.
Example:
function first(callback) {
console.log('Running first');
if (callback) {
callback();
}
}
function second() {
console.log('Running second function');
}
first(second);
The first function checks if a callback is used and then runs it. If there is no callback function nothing happens. You can chain functions this way.
You can also use anonymous functions.
first(function () {
console.log('This function that will run after the first one);
});
If you use setTimeout() you can't be sure whether the previous function has completed. A better way would be to use promises.
Understanding Promises
I hope I understood your question right. Good luck!
First of all setInterval can not be done by itself, it will fire infinitely if you not clear it with clearInterval.
But if you have some async action inside your function and whant to wait for it and then call another function you may just promisify it like Avraam Mavridis suggested.
function step1() {
var deferred = $.Deferred();
setTimeout(function () {
alert('I am step 1');
deferred.resolve();
}, 1000);
return deferred.promise();
}
function step2() {
alert('I am step 2');
}
step1().done(step2);
JsFiddle

Nesting callbacks for more than two tasks

It is possible to determine the order of TWO tasks using callbacks, as shown below.
a(b);
function a(callback) {
// do something
callback();
}
function b() {
// do next
}
See Fiddle
First do a(), then do b().
I would like to concatenate more than two tasks.
As I´m dealing with quite big functions, I´m looking for something like that:
a(b(c));
First do a(), then do b(), then do c().
However I'm not successful with this. See Fiddle
Is there an easy way to do so, maybe without needing Promises?
You're calling b immediately, not passing a callback to a. You'll need to use a function expression:
a(function(aResult) {
b(c);
});
Of course, you can avoid these by returning closures from all your functions:
function a(callback) {
return function(args) {
// do something
if (callback) callback(res);
};
}
function b(callback) {
return function(aResult) {
// do next
if (callback) callback(res);
};
}
function c(callback) {
return function(bResult) {
// do next
if (callback) callback(res);
};
}
which you would call like this:
a(b(c())();
(this is known as pure continuation passing style)

How to improve the following callback pattern?

I have the following pattern which strings together function1, 2 and 3 through their callbacks.
Assume that function1, 2 and 3 can take up to 1 second to complete. I would like to know other "better" ways of doing the same so that it doesn't turn into a monster when more callback functions are nested.
function1(function(cbData1){
if(cbData1){
function2(cbData1, function(cbData2){
if(cbData2){
function3(cbData2, function(cbData3){
// success
}
} else {
// failed for reason#2
}
});
} else {
//failed for reason#1
}
});
//example function
function function2(data, callback) {
// do dirty things
callback(newData);
}
If I understand you correctly you need to organize the callbacks in a chain. Look at Chain of Responsibility pattern.
So you will create an object containing the function to execute and callback function to execute if needed.
The last time I played with really nasty callbacks, I ended up doing something like this:
// Typed on the fly, be kind
var callbackList = []; // A list of functions to call in order.
function doNextCallback() {
if (callbackList.length) {
var f = callbackList.shift(); // Get the next callback function
window.setTimeout(f); // Give breathing space.
}
}
// Set up our callbacks
callbackList.push(f1);
callbackList.push(f2);
callbackList.push(f3);
// Start it happening.
doNextCallback();
function f1() {
console.log("Busy busy");
doNextCallback();
}
function f2() {
console.log("Busy busy");
doNextCallback();
}
function f3() {
console.log("Busy busy");
doNextCallback();
}
I had it all wrapped up in a nice object, but you get the idea.
This also made it very easy to re-arrange callbacks or to call just two of them in a big loop for testing purposes.

Any way to avoid using anonymous functions in jQuery?

If I have a chunk of code like this:
.hover(
function () {
hoverState($("#navbar a").index(this),1);
},
function () {
hoverState($("#navbar a").index(this),-1);
});
Is there any way to get rid of the anonymous functions and just say:
.hover(
hoverState($("#navbar a").index(this),1),
hoverState($("#navbar a").index(this),-1);
);
No, because otherwise your call:
hoverState($("#navbar a").index(this),1)
would evaluate at the same time as the call to the hover function itself. Since Javascript supports closures and first-class functions, you could make a wrapper function:
function wrapper(position){
function _f(){
hoverState($("#navbar a").index(this), position);
}
return _f;
}
And then use:
.hover(
wrapper(1),
wrapper(-1),
)
But the gains of such an approach are questionable.
The reason for the anonymous function is to defer the call to hoverState until the hover event happens. Without some function reference there, you end up calling hoverState and the result of the function call becomes the parameter to the hover method, which is certainly not what you want. The alternative would be to have a named function, but that's really no better and, in some ways, actually worse.
There's a way to do something like this, with the jLambda plugin.
// Without plugin:
$('.foo').click(
function() {
$(this).hide();
$('p').show();
$('a').width(20);
});
// With plugin:
$('.foo').click($l.hide().$('p').show().$('a').width(20));
My answer can seem stupid but here goes... you can use simple functions :}
function hoverStateProxy1() {
hoverState($("#navbar a").index(this),1);
}
function hoverStateProxy2() {
hoverState($("#navbar a").index(this),-1);
}
.hover(hoverStateProxy1, hoverStateProxy2);
As long as you passing reference to function you are OK. It can be both anonymous or not.
You could use JavaScript's "Apply" Function. Here is an example taken from the Prototype.js framework (bind implementation, though it should probably be renamed if not being used from within the framework).
EDIT: Corrected, see This Post
if (!Object.bind) {
Function.prototype.bind= function(owner) {
var that= this;
var args= Array.prototype.slice.call(arguments, 1);
return function() {
return that.apply(owner,
args.length===0? arguments : arguments.length===0? args :
args.concat(Array.prototype.slice.call(arguments, 0))
);
};
};
}
Usage:
.hover(
hoverState.bind(this,$("#navbar a").index(this),1),
hoverState.bind(this,$("#navbar a").index(this),-1)
);

Categories

Resources