0

I think everything is in my title, I'm always !@#$%^&* stuck with those kind of callback chains in my codes and call to external libraries. Of course as far as it stays synchronous everything is fine, when it comes to asynchronous calls ... headache comes !

I tried to do some obvious an simple samples, thanks.

var B;

(function(cb) {
cb(function(cb){
    cb(function(cb){
        cb();
    });
});
}(function(){
setTimeout(function(){
    B = 10;
}, 1);
}));

var C;

(function(cb) {
cb(function(cb){
    cb(function(cb){
        cb(function(){
            cb(function(cb){
                cb();
            })
        });
    });
});
}(function(){
C = 10;
}));

var D = function(){
this.E = undefined;
var that = this;

(function(cb){
    cb(function(cb){
        cb();
    });
}(function(){
    setTimeout(function(){
        that.E = 10;
    }, 1);
}));

console.log('this.E : '+this.E);






this.F = undefined;
var that = this;

(function(cb){
    cb(function(cb){
        cb();
    });
}(function(){
        that.F = 10;
}));

console.log('this.F : '+this.F);


}

new D();


console.log('B : '+B);
console.log('C : '+C);

Result :

    B : undefined
    C : 10
    E : undefined
    F : 20
James Montagne
  • 77,516
  • 14
  • 110
  • 130
Amaury Brisou
  • 344
  • 1
  • 4
  • 10
  • someone will go on about promises, but you can do a lot of simplification by naming your functions instead of using nested anon functions. doing that, and closing any common state between them, you won't need to nest at all and can give each step a nice name for debugging. – dandavis Jun 23 '14 at 18:11
  • Your question is far too abstract (not real code solving a real issue) to provide anything more than platitudes as answers. Please write about an actual piece of code with an actual problem to solve and you will get much better ideas for how to simplify. For example, in your `cb()` example, why not just loop five times rather than recurse? – jfriend00 Jun 23 '14 at 18:33
  • those kind of pattern seems also named [pyramid of doom](http://calculist.org/blog/2011/12/14/why-coroutines-wont-work-on-the-web/) – Amaury Brisou Jun 23 '14 at 18:36
  • http://stackoverflow.com/questions/5951350/executing-asynchronous-calls-in-a-synchronous-manner/27501874#27501874 – Abhimanyu Dec 17 '14 at 08:39

0 Answers0