One of the good things and down fall about javascript is that it executes line by line. If you are waiting on external source ( like api call ) to finish processing, then this line by line processing data could present a major problem for you as some of your code may fail.

Has this happened to you before? If so, read on to learn how to solve this problem.

You can easily solve your above problem with javascript callback functions.

What is a javascript callback function?

A callback function does a series of calculations just like you would do in a regular javascript function, however with callback function, the JavaScript will not continue until the callback function has finished doing its thing.

How do I use it ?

The easiest way to use callback is as follow:

//Create callback function
function call_back_func(callback)
 var d = 1;
 callback(d); //<---where the magic happens

//Call the callback function like this:
 //data is here is value of variable d
 //in this case it will be 1

When To Use Regular Vs Callback Function?

When you are having to deal with any kind of calculation locally, always use a function that returns a value.

For example:

//Create function
function reg_func()
 var d = 100;
 return d; 

//Call the function like this:
 var v1 = reg_func();

When you are making a call to an external source, always use a callback function, because that way your code will not continue until that process of external source has finished doing whatever it needs to do.





Post Comment