Asynchronous JavaScript - Callbacks, Promises, and Async/Await

Asynchronous JavaScript - Callbacks, Promises, and Async/Await

For Beginners

Introduction

As we know, JavaScript is a synchronous, single-threaded language, Which means that instructions can only execute one after another. Imagine if any event takes too much time in execution then it will block all upcoming events and make discomfort in our code. In the case of a website, this problem will cause an interruption in interaction with the web pages.

Asynchronous programming with JavaScript

For solving the above problem asynchronous came into the picture. Asynchronous programming makes it possible to express waiting for long-running action without freezing the program during these actions.

freeCodeCamp-Cover-2.png

Callbacks

callback.png The callback is a function that is passed inside another function as an argument for executing later. This method is very efficient, but only to a certain point, sometimes developer has to make multiple calls to make these call callbacks they need to be nested which makes it very hard to read and maintain.

The process of nesting callbacks is also referred to as the callback hell which forms the pyramid structure and every callback depends/waits for the previous callback.

Promises

It is one of the ways to deal with asynchronous code which cop with the problem of callback hell.

Promise is a special Javascript object which produces the values after asynchronous code completes execution

promises.png

Once a promise is called, it will start in a pending state while the calling function will continue executing, and the promise will reside in a pending state until it resolves. Eventually, the created promise will be ended in resolved or rejected state forward by calling the respective callback function passed to then and catch upon finishing.

Promise Chaining

javascript-promise-chaining.webp

Promise chaining is the situation where a promise is returned to another promise which creates a chain of promises.

Async and Await

When there is a long chain of promises just like nested callbacks it gets pretty bulky and confusing. That's why Async and Await were brought about.

Async Function

Let’s start with the async keyword. It can be placed before a function, like this:

Async functions.png

The async function will always return promises, The word “async” before a function means one simple thing: a function always returns a promise.

Await

Syntax Await.png

Await keyword always makes sure a function waits for the promise until it returns its result.

Here’s an example with a promise that resolves in 1 second:

Await (1).png

THANKS FOR READING!!