Javascript — Callbacks, Promises, Async/await

Callbacks, Promises, Async/await are ways to handle async programming in Javascript.

Sync / Async

In synchronous programming, the parent process will wait for the child process to complete before it continues. In contrast, in asynchronous, the parent process will not wait for the child process to complete.

Advantage & Disadvantage of Async

The benefit of async programming is that you can run multiple processes without waiting for each other.

On the other hand, there is a disadvantage: there may be a chance that the dependent process may run before completing the relevant process if there are dependencies between operations.

Let me explain with a simple example, Consider you need to display Student details, which involves two operations,

  • Get the grade (Child process) — It completes in 2 seconds
  • Display student data (Main Process) — It completes in 1 second

Output:

The reason for Grade displays as undefined is displayStudentData completes before calculateGrade completes.

How can this be resolved? you are correct, and The answer is Callbacks

Callbacks

A callback is a function passed as an argument to another function. The callback is the way to control async calls when the parent method is dependent on the child method returns.

For our case, displayStudentData is dependent on calculateGrade returns. displayStudentData can be passed to calculateGrade as callback and called after grade calculation.

Now grade details will be shown as expected because of the callback.

Output:

Callback hell

The callback is good when we have one async call. But in the real world, you can’t stop making multiple async calls in the function. When you make numerous callbacks, your code will be so messy and hard to read. In javascript, when there are multiple callbacks, we call that Callback hell.

How can this be resolved? you are correct, and The answer is Promises

Promises

Promises are introduced in ES6 to handle Asynchronous Programming more elegantly.

In our example, we can change calculateGrade to return Promise and call displayStudentData after calculateGrade resolved.

Note: To keep it simple, I didn’t handle reject in the above code.

Output:

Async / Await

Async / Await is another way of handling responses from Promises.

To use await, the function should be declared as async. The below code will explain how Async / Await is used to handle promises.

Output:

Software engineer who passionate about learning technology. I strongly believe that Technologies are not just to learn, Technologies are to make our life easier