Asynchronous in JavaScript

Async/await is a new way to write asynchronous code. It is built on top of promises, therefore, it is also non-blocking.

Previous options for asynchronous code were callbacks and promises.

Callbacks

A callback is a function that is passed inside another function and then called in that function to perform a task.

The setTimeout is a JavaScript function that takes two parameters. The first parameter is another function, and the second is the time after which that function should be executed in milliseconds.

The function inside setTimeout in this case is required to run after one second (1000 milliseconds).

It is carried off to be executed in some separate part of the browser, while the other instructions continue executing. and After one second, the results of the function are then returned.

If you run the program, you will get this:

The “last result” is logged before the function in the setTimeout returns its result.

We used this method to fetch data from a database. While the user is waiting for the database call to return results, the flow in execution will not be interrupted.

This method was very efficient, but only to a certain point. Sometimes, developers have to make multiple calls to different sources in their code. In order to make these calls, callbacks are nested until they become very hard to read or maintain. This is referred to as Callback Hell.

Nesting callbacks within callbacks will soon start to look like this:

Credit: https://medium.com/free-code-camp/how-to-master-async-await-with-this-real-world-example-19107e7558ad

To fix this problem, promises were introduced.

Promises

Promises are objects that represent the eventual outcome of an asynchronous operation.

Promise has three states of operation.

Pending: The initial state of the operation has not been completed yet. Like the dishwasher is running but has not completed the washing cycle.

Fulfilled: The operation has been completed successfully and the promise now has a resolved value. Like the dishwasher has completed the washing cycle and is full of clean dishes.

Rejected: the operation has failed and the promise has a reason for failure. Like the dishwasher encountered a problem and returns unclean dishes.

credit: How To Master Async/Await With This Real World Example

Promises came along to solve the problems of callback functions. A promise takes in two functions as parameters. That is, resolve and reject. Remember that resolve is a success, and reject is for when an error occurs.

Afterwards, we can call .then() and .catch() on that promise function:
then — Runs a callback you pass to it when the promise has success.
catch — Runs a callback you pass to it when something went wrong.

Promises are a neat way to fix problems brought about by callback hell.

But there is an even better way! You might be familiar with the following method but before that, I want to talk about another Promise method like “Promise.All”.

Promise.All

As per MDN documentation:

The Promise.all(iterable) method returns a single Promise that resolves when all of the promises in the iterable argument have resolved or when the iterable argument contains no promises. It rejects with the reason of the first promise that rejects.

Case one:

When all the promises are resolved.

Sunglasses Order code

In the code, you will see there are 3 orders of sunglasses, and all of them are pushed in the same array name promiseArray, and after that, the promiseArray is passed in Promise.all() methods to make a process.

Promise.all() methods will process until the error occurs or all the promises are resolved, and this is the case when all promises are resolved.

All promises are resolved because every order passes the condition of myOrder() function.

Case two:

When there are no promises.

This is the case where no promise will be assigned to Promise.all() method.

Since there are no promises in the array the returning promise is resolved.

Case three:

It rejects by using the reason of the first promise that rejects.

This is the case where the error occurs. When the Promise.all() methods got first rejected, it will stop and return with a reason of the first promise that rejects.

In the code, you will see that there is a crazy amount of sunglasses ordered. It definitely that order will be got rejected.

The Promise.all() method didn’t continue the process after getting rejected and returned with a reason for the first promise that rejects.

Async-Await

The Async function provides us with a clean and concise syntax that enables us to write less code to accomplish the same outcome we would get with promises.

Async functions are created by writing the word async before the function declaration like this:

Asynchronous functions can be paused with await, await keyword can only be used inside an async function it returns the resolved value of a promise.

In waiting() we pause our function until the first promise resolves, then we construct the second promise.

But in concurrent() both promises are constructed by using await.

Async/Await looks similar to synchronous code, and synchronous code is much easier to understand.

reference

--

--