- What is the difference between synchronous and asynchronous functions?
Synchronous function runs only one section of code at any one time. Tasks are executed one at a time( example by a click function) , and the next task requires the user to click once more( if using another click function) so that the next task is executed. And the browser won’t respond to any events whatsoever while it completes the first action.
Asynchronous functions can be initiated and tasks can be put aside until a later timing, while the browser can get the next task done on the to do list, during the waiting
In JS, the browser’s to-do list is called the event loop. Though the browser can still only do one task at a time, it does not need to wait till task 1 is completed before it executes the subsequent tasks. Hence, The flow is continuous in asynchronous functions because the JavaScript engine actually sports an additional background thread which takes care of managing the event loop.
- What is callback hell?
A straight forward request to record each user’s log in to the database would require a three nested functions program, one function being the main function that nests the whole operation, second to look up user in the data base, and third one to record the user log in data.
A more complex request could require many more functions, example, 1 main function, with 30 more sub functions to do many different tasks. The subsequent functions after the main function are called callbacks. When the complexity is multiplied due to huge number of call backs required , it is known as call back hell.
3. Which technique can help us solve callback hell?
In the browser, a common pattern to deal with excessive callbacks is to use promises . jQuery ships with a simple built-in promise library that enables us to chain callbacks and deal with errors.