When a program is executed by the processor it runs straight, with only one thing happening at a time. There are many programs that interact with the things outside other than the processor like a network request, data read from the hard disk. In this era in which computers have multiple processor cores available there’s no sense sitting there waiting for something when you could let the other task come along on another processor core and let you know when it’s done.

This lets us get other work done in the meantime, which is the basis of asynchronous programming. It is up to the programming environment we are using (web browsers/node in our case) to provide us with APIs that allow us to run such tasks asynchronously.

There are two main types of asynchronous code style one can come across in JavaScript code, old-style callbacks, and newer promise-style code. Let us review each of these in turn.

Callbacks:

A callback is a function that is to be executed after another function has finished executing — hence the name ‘call back’.

It is a function passed into another function as an argument to be executed later.

The function that takes a callback function as an argument is known as a High-Order function.

Callbacks are a way to make sure a certain code doesn’t execute until the other code has already finished execution.

Ideally, the function that performs an async action takes an extra argument, a callback function. When the action finishes, the callback function is called with the result.

Let us see an example:

fs.readFile('/input.json', function (error, data) {
  if(error) {
    //handle error logic
    console.log(error);
    return;
  }
//no error process data
  console.log(data);
})

In the above code snippet, we are using the readFile method in fs class (available as node API). This method reads a file asynchronously. It takes a callback function as an argument (here second argument) which is being called when the reading of the file is completed or there is an error in the process.

The problem with the callback arises only when we have a callback having another callback function as an argument creating a nested callback structure known as “Callback Hell”. As the number of nesting increases, it becomes difficult to manage and understand. It looks something like this.

firstFunction(args, function() {
  secondFunction(args, function() {
    thirdFunction(args, function() {
      // And so on…
    });
  });
});

Promises:

Promises are a first-class representation of a value that may be made available in the future.

It allows us to associate handlers with an asynchronous action’s eventual success value or failure reason.

This lets asynchronous methods return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point in the future.

#promises #asynchronous #javascript #programming

Asynchronous Programming in JavaScript
1.10 GEEK