Getting Started with Asynchronous programming..

What is async programming..

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

-------------------------------------------------

Now consider the following example..

 

console.log("one");

callSomeFunction(params, function(respone) {
  console.log("two");
}

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.

Deeper analysis

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.


What is a callback function?

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.


Why asynchronous?

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.

Best Practices..

Always expose error first callbacks

 

function doSomething(params ..., callback) {
  //do something..
  callback(err, response)
}

..........

doSomething(params, function(err, data) {
  if(err) {
    //handle error..
    return;
  }
  //handle correct response
});


Coding standards... Challenges.. Making life easier with callbacks

Async Programming Activities

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

Reference Links : (Right Click is disabled ,So Ctrl+C and Ctrl+V the links)

Practice Questions :

Arithmetic operators using Async programming..

Solve the following set of methods to get brief understanding about the Async programming..

Project consists of the below execises