What are Callbacks, Promises, and Async/Await in JavaScript?

Asynchronous JavaScript

This Blog will explain the fundamentals of asynchronous operations in Javascript which include Callbacks, Promises, and Async/ Await to handle deferred operations in Javascript. I will explain to you all three terms in detail with examples.

What are Callbacks?

A callback function is a function that is passed to another function so that when the first function is executed, the second one which is passed to the first one will also execute. Normally callback runs after the parent function completes its operation. This means that we can pass functions as parameters to other functions and call these passed functions in the other functions.

Let’s understand with an example. Let’s consider we have one array called books.

Now, we need the title of the books after 1 second. so, we make a function getBooksTitle().

when We call function getBooksTitle(), we will get the following output after 1 second.

Output:

To Kill a Mockingbird

The Great Gatsby

Now, Let's create a function to add a book after 2 seconds in our books array.

But, here it will not show because our above function executed in 1 second and this is executing in 2 sec. So, here Callback is coming into the picture. Now with the callback function, we can make an asynchronous operation.

so, with the callback function, a new book added after 2 seconds in the books array and we can see that the getBooksTitle() function is passed in function addBook(). After invoking addBook(), we will get the following output.

Output:

To Kill a Mockingbird

The Great Gatsby

The Adventures of Huckleberry Finn

What are Promises?

When is a promise in JavaScript, it’s either it would be fulfilled Request when the time comes or it won’t. A promise is used to handle the asynchronous operation. With JavaScript, it is not necessary for us to wait for an asynchronous block of code to completely execute before other synchronous parts of the code can run. With Promises, we can defer the execution of a code block until an async request is completed. This way, other operations can keep running smoothly and without overloading the server. A Promise is an object which takes a callback and executes it asynchronously. It is considered easier to use and maintain than callbacks.

There are mainly 3 states of promises.

  1. Pending: Initial state before the Promise succeeds or fails.
  2. Resolved: completed Promise
  3. Rejected: Failed Promise

Now, Let’s understand with an example. Let’s Declare books array and function getBooksTitle() to get book titles. After we create a function addBook() to add a book to our array, with Promise.

So, here we noticed that promise took callback function with two parameters resolve and reject. So now we add book in our books array with addBook() Function.

Here, we can see that, we didn’t passed callback function but we used promise and after this code execution we get following output.

Output:

To Kill a Mockingbird

The Great Gatsby

The Adventures of Huckleberry Finn

So, after the promise resolved it invoked getBooksTitle() function and we get all 3 books title. And with .catch, we can catch error as well. If its rejected then we get error message what we passed in reject.

Let’s see an example how to fetch API with promises.

So with this syntax we can fetch data of users with this method.

What is Async/Await?

Async functions return promises, and Await is syntactic sugar for waiting for a promise to be resolved. Async/Await method came into picture because the main intension is to make our asynchronous code look more like synchronous code, which is easier for humans to understand.

When using this method, the function is wrapped with the “async” keyword. This lets JavaScript know that we want the function to be an Async one and that we also want to be able to use the Await keyword which means that we cannot use Await in a function without first putting that function in an Async wrapper.

Async/Await is more elegant way to handle promise. Let’s See an example.

In output we get array of users. So, Simple async/ await is simpler way to write promise.

Conclusion:

Hopefully, we now understood the concept of callbacks, promises and async/await and how to use them in our program. These concepts usually work with asynchronous requests and is heavily used for fetching or posting data to a server via an API endpoint.

Sources: https://codeflarelimited.com/

MERN stack Developer || writing about Javascript, MongoDB, React, Express and NodeJS related articles

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store