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())
2
Answers
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.
The above code is going to print the output as required.
Use async package. In async library there is a way as:
Using this you can add as many as functions and run it in series/waterfall model(Lets say function a,then b and goes on).Like in the code snippet above add as many as functions you needed and once callback() is called then only it will go to second function then to third and like that.And at last it reaches the function error part if there is error you can pass error to callback to exit from there.Check this out will be better and more clean way to do your requirement.