Before understanding async programming, first lets see the traditional way of programming, i.e., synchronous calls. Example below.
console.log("one"); console.log("two"); console.log("three"); |
The output of the above code snippet would be
one
two
three
console.log("one"); callSomeFunction(params, function(respone) { console.log("three"); |
The output of the above snippet would be..
one
three
two
The main difference is that, the statement console.log("three"); does not wait for the complete execution of
callSomeFunction(params, function(respone) {
console.log("two");
}
Here console.log("two") statement is waiting for the function callSomeFunction() to be completed. As this is async behaviour, console.log("three") gets invoked by the main thread.
If the method callSomeFunction has a I/O process to be executed, the Main thread of the JavaScript Runtime, delegates the method's execution to a worker thread. So, now the main thread is free to execute next statements. Hence, three would be printed earlier than two in the above example.
In the above example, since callSomeFunction method is async, it cannot return value to the main thread. In this context, we will make use of callback function. It is a function handler that is invoked after the async method is executed completely. The results of the async method are passed to the callbacks as parameters.
Synchronous blocks potentially block the further execution of the other statements until and unless they are completely executed. The primary disadvantage with such blocking calls is that, it makes client's UI completely sluggish.
Always expose error first callbacks
function doSomething(params ..., callback) { .......... doSomething(params, function(err, data) { |
This project aims at understanding the asynchronous programming pattern which is essential in understanding various frameworks
Each exercise helps you in understanding async programming pattern while using various resources such as files,network etc