Search code examples
javascriptcallbackanime.js

How do I call a function on completion of tasks on some other function through callbacks?


I have a function called scrollText() defined like this:

function scrollText(p1, p2) {
   // Do stuff

   anime({
   // key-value pairs
   complete: function(anim) {
      showPopup(p3, p4, p5);
   }
   });
}

Then, let's say I have showPopup() defined like this:

function showPopup(p3, p4, p5) {
   // Do stuff

   anime({
   // key-value pairs
   complete: function(anim) {
      ShoutLoud(p6, p7);
   }
   });
}

Basically, I call scrollText() which calls showPopup() when anime fires the complete callback. The same thing happens inside showPopup() but this time,I call ShoutLoud(p6, p7) on complete.

The structure is vary rigid at this point.

I might not always call scrollText() inside showPopup(). Sometimes, I might call ShoutLoud() or other function.

Also, the parameters will be dynamic and are passed at run time based on user interaction.

The callback functions might not always get called so it is optional.

How do I achieve this?

I could do the parameter calculations inside complete but that would place the code for all the calculations for all the interactions inside complete.

I want to do something like this:

function scrollText(p1, p2, `showPopup(p3, p4, p5, ShoutLoud(p6, p7))`) {
   // Do stuff

   anime({
   // key-value pairs
   complete: function(anim) {
      showPopup(p3, p4, p5);
   }
   });
}

This is becoming callback hell. I don't think it is maintainable in the long run. Is there a better alternative?


Solution

  • Pass the callback function as an extra parameter to your functions:

    function scrollText(p1, p2, complete) {
      // Do stuff
      anime({
        // Key-value pairs
        complete
      });
    }
    function showPopup(p3, p4, p5, complete) {
      // Do stuff
      anime({
        // Key-value pairs
        complete
      });
    }
    

    Then you can invoke them like

    scrollText(p1, p2, () =>
      showPopup(p3, p4, p5, () =>
        ShoutLoud(p6, p7)
      )
    )