Search code examples
javascriptcallback

Stringing Callbacks together across multiple functions


I want to string functions together using callbacks - which I am still struggling to learn. Essentially I want the functions to execute one after another in order a, b and c. When I run the basic code below, my output is

poll b poll a

poll c is never returned.

What am I doing wrong that makes the order wrong and c to never be returned?

function a(callback) {
  console.log('poll a')
  if (callback) {
    callback(b())
  }
}

function b(callback2) {
  console.log('poll b')
  if (callback2) {
    callback2(c());
  }
}

function c() {
  console.log('poll c')

}
a(b())


Solution

  • In the above code, you are calling b inside a's function call which calls function b first and prints "poll b". But there is no argument passed to function b here so callback will be empty so the condition becomes false and function c will not be called. The return value of b will be null here.

    Once function b is executed and returns null, function a will be called as a(null). While executing function a, "poll a" will be printed next and the callback variable will be checked for truthiness. As callback has null, again the condition fails and the execution stops there after calling a.

    So the code needs a little modification as to work in the specified manner.

    function a(callback) {
        console.log('poll a')
        if (callback) {
            callback(c)
        }
    }
    
    function b(callback2) {
        console.log('poll b')
        if (callback2) {
            callback2();
        }
    }
    
    function c() {
        console.log('poll c')
    }
    
    a(b)
    

    The above code is going to print the output as required.