Async JavaScript Part 1: The Callback

callback

What is Callback?

Callback is a function that is to be executed after another function has finished executing.

JavaScript functions can take other functions as arguments and can be returned by other functions. These functions are called higher-order functions. Any function that is passed as an argument is called a callback function.

** Let's see simple example**

function first(){  
 console.log(“First function finished”);  
}function second(){  
 console.log(“Second function finished”);  
}first();  
second();

So we have two functions named first and second that are printing log. As you would expected, the function first is executed first, and the function second is executed second.

// First function finished  
// Second function finished

But what if first function contains some code that won’t execute immediately? For example, an API request where we have to send the request then wait for a response? Let's use the setTimeout function and pretend that it is a server response. With setTimeout we are simply saying to this after x time in our case 1000ms or 1s.

function first(){  
 setTimeout(function() {  
 console.log(“First function finisher”);  
 }, 1000);  
}function second(){  
 console.log(“Second function finished”);  
}first();  
second();

And we got:

// Second function finished  
// First function finished

Even we called first function first, we got the result of that function after the second function.

Create callback

function first(callback){  
 setTimeout(function() {  
 console.log(“First function finisher”);  
 callback();  
 }, 1000);  
}function second(){  
 console.log(“Second function finished”);  
}first(second);

Now we have callback argument in first function and we are passing second function as callback. After setTimeout has finished callback is executed and now we got:

// First function finished  
// Second function finished

You can now understand what a callback is and how it works.

Next part: Async JavaScript Part 2: Promises.




#javascript #async

Author: Aleksandar Vasilevski |

Loading...