JavaScript is single threaded.
The browser can be divided into three parts:
Event Loop
Web API
Event Queue
The event loop runs for forever, i.e., kind of an infinite loop. The event queue is where all your functions are pushed on some event (example: click).
This is one by one carried out of queue and put into the event loop which executes this function and prepares itself for the next one after the first one is executed. This means execution of one function doesn't start until the function before it in the queue is executed in the event loop.
Now let us think we pushed two functions in a queue. One is for getting a data from the server and another utilises that data. We pushed the serverRequest() function in the queue first and then the utiliseData() function. The serverRequest function goes in the event loop and makes a call to server as we never know how much time it will take to get data from server, so this process is expected to take time and so we busy our event loop thus hanging our page.
That's where Web API come into the role. It takes this function from the event loop and deals with the server making the event loop free, so that we can execute the next function from the queue.
The next function in the queue is utiliseData() which goes in the loop, but because of no data available, it goes to waste and execution of the next function continues until the end of the queue. (This is called Async calling, i.e., we can do something else until we get data.)
Let us suppose our serverRequest() function had a return statement in code. When we get back data from the server Web API, it will push it in the queue at the end of queue.
As it gets pushed at the end of the queue, we cannot utilise its data as there isn't any function left in our queue to utilise this data. Thus it is not possible to return something from the async call.
Thus the solution to this is callback or promise.
- An image from one of the answers here correctly explains callback use...*
We give our function (function utilising data returned from the server) to a function calling the server.
Image may be NSFW.
Clik here to view.
function doAjax(callbackFunc, method, url) { var xmlHttpReq = new XMLHttpRequest(); xmlHttpReq.open(method, url); xmlHttpReq.onreadystatechange = function() { if (xmlHttpReq.readyState == 4 && xmlHttpReq.status == 200) { callbackFunc(xmlHttpReq.responseText); } } xmlHttpReq.send(null);}
In my code it is called as:
function loadMyJson(categoryValue){ if(categoryValue === "veg") doAjax(print, "GET", "http://localhost:3004/vegetables"); else if(categoryValue === "fruits") doAjax(print, "GET", "http://localhost:3004/fruits"); else console.log("Data not found");}