0

I'm trying to run away from pyramid of doom. Imagine the following function call series:

$.wait(1000).done(function() {
    //Do something

    $.wait(5000).done(function(){
        //Do something else

        $.wait(2200).done(function(){
            //Do something else
        });
    });
});

Where the $.wait function is defined as:

$.wait = function (duration) {
    return $.Deferred(function (dfd) {
        setTimeout(dfd.resolve, duration);
    });
};

The question is that how can I refactor the above code so that it becomes readable/maintainable?

Joe Bank
  • 653
  • 7
  • 20

1 Answers1

1

Well, you already have promises (or at least, deferreds) in your code, so there is no good reason to look for different coding pattern. You can however flatten your callback pyramid by chaining the promise callbacks with the allmighty then method instead of nesting them (with done):

$.wait(1000).then(function() {
//           ^^^^
    //Do something
    return $.wait(5000);
//  ^^^^^^
}).then(function() {
// ^^^^
    //Do something else
    return $.wait(2000);
//  ^^^^^^
}).then(function() {
// ^^^^
    //Do something else
});

which is exactly equivalent to your code.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375