asynchronous programming
Photo by Ferenc Almasi on Unsplash

Javascript and Asynchronous Programming

Abdurrahman POLAT
Orion Innovation techClub
7 min readApr 3, 2022

--

Hello, my name is Abdurrahman. Currently, I’m an intern at Orion Innovation Turkey. I am very lucky to be a part of such a big family.
I would like to thank my manager, mentor, and teammates who contributed and supported this article I wrote. I wrote this article to give a different perspective to friends researching asynchronous programming.

Synchronous programming is the execution of codes in a specific order and hierarchy. On the other hand, the situation is the opposite in asynchronous programming. Executing and calling a function does not occur in a specific order. More than one operation can be performed at the same time. When you start an action, your program continues to run and the program is notified when the action is finished. There are some constructs in Javascript that allow us to control this state. I would like to start the article by explaining how the javascript runtime engine works.

Javascript Runtime Environment

Javascript runtime has two parts called heap and stack. The Heap section is where the written code is kept. The part where the functions are located is called Stack. Since its reference is accessed while calling a function, the part inside this reference can be accessed from the heap section.

Javascript and asynchronous programming

Web API’s

In this section, AJAX operations and events take place. Structures based on waiting for a certain time, called set timeout, etc., are the operations offered by the Web API. Considering the engine of the javascript, it should be decided whether it is synchronous or asynchronous. Besides XmlHttpRequest serves by Web API.

Javascript has a single trade structure, so only one transaction takes place at the same time.

⦁ Callback, promise, async/await → Used to manage asynchronous programming.

⦁ XmlHttpRequest is used for HTTP operations. It is used for operations such as to get, post, etc.

⦁ Fetch API → It is also used for HTTP operations.

⦁The Axios library is used to facilitate HTTP operations.

When I define a variable named Surname, I can make it wait for this variable with a set time out. If I write console.log part in set time out, I can see the text PULAT on the screen. If I write it outside, I can see the value of the variable when I write surname on the console.

I created a variable called Function getName, I added setTimeout in it, which means I stated that it is a delayed operation, then I added a callback to the function, I will send the reference of a function, I will define the reference of this function under setTimeout and send the surname, then the callback will be called after the assignment is made. In this way, after the process is completed, the callback function will be activated after the new assignment is made.

Where will the callback be defined?

I am sending a parameter to the getName function using the arrow function to define the callback. The arrow function I defined below is now a parameter of the getName function, now I have defined it as a surname, this could be anything but a surname.

If it was tried to print the surname directly into the above function, it would be empty, and then the function would be printed. With the help of callBack, this can be prevented.

The output is as follows.

WHY WE SHOULD NOT USE CALLBACK?

It will cause a structure called callback hell, for example, the above data may have to wait for each other. For example, data that will come from the top may be a parameter that is necessary for other data to come. This situation will have to wait for each other.

PROMISE

Promise has a stage called pending. Here, we come across two stages called to resolve and reject. Successful and unsuccessful situations can be managed using them. When Resolve is called, the process can be said to be successful. We can think of this as returning a callback. This returned value is also captured in then(). Resolve corresponds to then reject corresponds to catch.

I defined a variable called let data. Then I define an arrow function called const getData. Then I create a promise object and define resolve and reject. Here again, there is a callBack function and it takes parameters. Each of these parameters will be a function. I open if-else blocks and return resolve with the true condition and reject with the false condition. Notice that I am returning a promise object when using getData with the return. When I print the getData function with the console log, it will return me a promise object.

When we look inside the Promise, we see fulfilled, which means that the transaction has taken place. In the Result section, we can see the value we sent. Resolve can be obtained by getting data. After Resolve, data returns, which is a string, we can print it with console.log. Before doing these steps, I need to return the data I defined with let as true. Continue with catch (err ) in the continuation of the chain. The catch works when the Reject returns.

As a second example of promise, you can examine the following example.

A small part of the output is available below.

FETCH API

⦁ In the fetch structure, a Promise object is returned in the background.

⦁ An asynchronous operation is included in the Web API.

⦁ The URL is written in fetch and the response in the then() is also printed.

⦁ The catch is added at the bottom, where an error message can be written with console.log. Or err can also be given.

The output is as follows.

⦁ A request can also be made in Fetch or you can choose from your local files.

⦁ Fetch returns a promise object in the background, so there is no need to re-create the promise.

⦁ In the Then(), the incoming response is printed.

⦁ There is a promise object in the form of Pendik, but the result of this is reached via the response.

⦁ The response is caught with them because it is a promised object.

⦁ We can display the data in the URL by saying return response.json(), and the return allows us to proceed to the next step.

⦁ If we want to print directly with console.log, we will see an array, so we use return.

Async/await and Fetch API

It is used by the Web API to manage the asynchronous structure.

I defined a function called Const getData. It is marked with the async keyword as it is an asynchronous operation. When using Wait, it is stated that it is an asynchronous operation and it is told to wait. response. As a result of this asynchronous operation, a value will be returned to the response. Then I used the keyword wait with data. Awaiting with await because a promise object will be returned from JSON. Then the data is printed with console.log Finally, a search is made with getData.

The output is given below.

If you want to send data instead of console.log, it can be used with then() by writing return data().

After returning the above value, the desired operation can be performed. For example, it can be called within another function.

ERROR MANAGEMENT

Response status can be checked by getting user-defined with Fetch API. Error management is made as successful if the Response. status is equal to 200, not successful if it’s not.

Finally, I would like to state that I was inspired by Mert Özen’s youtube video while writing this article. Thank you so much for inspiring me.

--

--