Asynchronous JavaScript!?

Asynchronous JS moves us away from DOM and made us work with AJAX , Fetch API which is used to make HTTP requests to files .

But what is synchronous programming?

See the example , you cannot do anything until the posts are fetched . This is also called blocking code. Because it is going to block until posts are fetched and loaded which obviously will make things go slow down.

Then what is asynchronous code?

Instead of pulling the code out of synchronous function , we are passing in callback function which is just another method of handling synchronous code.

This callback will run and fetch the post but allow us to do something with the post. With this program does not get blocked.

So most of the asynchronous code you would work comes from some API or library.

Few ways to work with Async code is:

  1. Callbacks
  2. Promises
  3. Async/Wait

AJAX STANDS FOR Asynchronous Javascript X-AMOUNT

Ajax is not a language or a framework or a library but a set of web technologies to send and receive data from client and server asynchronously. It is one of the behind the scenes thing without having to explicitly reload web page. In AJAX , JSON has pretty much replaced XML beautifully.

But how the heck AJAX works?

There is a client/browser and server for you . Usually we type in URL’s to request a common HTTP request to the server and we get the common response back and coding entire web page with headers in data.

AJAX allows us to make requests asynchronously. All of this is done behind the scenes without reloading the entire web page every time.

To update one little section of text ,we can do that with AJAX which is much easy than loading the entire web page. This thing happens when we make an AJAX call or async JS call which goes through AJAX engine and uses XML HTTP request object. Now the server returns the data in JSON format and then we parse and use that data in our application. All of this is done without any hit to reload or fresh.

Sending and Receiving request can be from local server or local machine or from some API , API’s have certain permissions granted to us when we try to use them.

There is also something called cross-enabled which allow us or cross -domain communication which means we can make requests to their API’s even when we are not on same domain as of them.

X-mount HTTP object is the core technology of AJAX provided by browsers JS environment. All browsers have this API. Its methods transfer data between client and server.

With so much discussion about AJAX, there are other libraries and methods that are used to make requests and Fetch API is one of them. Other external libraries include Axios , Superagent , JQuery and Node HTTP.

Fetch API is majorly suggested in vanilla JS.

Time for some action!?

How to get data from some text file and bring it to your web page asynchronously using XHR object :~

Remember this: data.txt has some text inside it .

Check HTTP status

// 200 :0K

// 400: Forbidden

// 404: Not Found

Ready state values:

// 0 : request not initialized

// 1: server connection established

// 2: request received

// 3: processing request

// 4: request finished and response is ready

Older Syntax: Use in place of onload()

when you click button , text from data.txt file is displayed on console

Optional : for loaders and spinners if we want ~

Optional : For errors~

But we want thing to display on web page not on console:

Working with AJAX and JSON Data:~

After playing something here and there , let us work on JSON data.

Goal is to have two JSON files , where one is single customer and one will be array of customer objects.

First we will create customer.json file,

So this is how we are getting data asynchronously through XHR object and outputting in browser.

It works the same way if you are fetching from some external API or library.

Here we are getting from local file.

But to fetch an array of customers:??

So this is how we can use JSON n=and how to fetch single or array of object from json file to web page.

What with a Public API?

Data from External API — Chuck Norris Jokes:-)

Rest API’s and HTTP Requests:

A contract provided usually consist of structured request and response. Our last web api is the perfect example to generate response in form of json format.

But REST stands for Representational State Transfer for designing networked application , relies on stateless client server protocol (HTTP), treats server objects as resources that can be created or destroyed. It is used anywhere virtually.

AS REST can be operated just from HTTP Requests and standard JSON virtually, It makes REST beautiful.

Remember API is the messenger and RESTS uses HTTP to format that message.

Different Types of Requests:~

BUT the main focus is on first-four!

API has something called as end-points to access certain things .

Note that with post, put and delete it is needed to send data along with your request because it needs to know the post data to add, update or delete. All URL are same but with different requests.

Callback Function:~

A function passed into parameter to another function and then it is ran inside the function body.

array ForEach where we pass the function is an example of callback!

Having a plain index.html is okay (only boiler plate).

And then in app.js:-

when it run we get on body of web page:

post One

post two

but where is post three? So the way it worked is server took 2 seconds to create the post and 1 second to get the post.

So the server got the post before post three was actually created! This is called as synchronous way.

With async way using callbacks:

With createpost() you can pass a callback such that :

with calling of createPost() takes another callback function as parameter . we will passing as function getPosts(). So when it is called , it will call getPosts() with in that 2 seconds.

With that post three will be included in web page asynchronously.

Easy HTTP- Custom AJAX Library:-

To build this , we need a REST API that takes get ,post , put and delete. So we need JSON Placeholder , a fake online REST API for testing and prototyping.

To start with we need index.html and two js files one for building library and one general app.js file.

Its time to build our library:

Here we first declare a function easyhttp() which will instantiate XHR object . And then we will work on GET request method such that we will use prototype method to define a function for GET request where on hitting tghe onload , everything is sent to app.js which wll call this GET request with a particular URL we used to bring in back the response of data from the GET request .

AS GET was able to get data from external API . For POST method,

PUT: update the custom post with id 6

Delete:

This is how a customized AJAX library is built!

Promises:~

It is an alternative to callbacks, way of handling asynchronous operations. And they are called promises because while they are handling asynchronous operations , they can promise to do something when the operation is finished.

Earlier building easyhttp AJAX library , we used callbacks a lot.

How to use promises then? To use promise remember we use two parameters resolve and reject , resolve is what we want to call in the print and reject we call when we want some kind of error to throw.

Here we declare a function createPost() which will ofcourse take post as a parameter and inside the function , we instantiate a and return promise with two parameters resolve and reject with a to do defined about pushing the post in 2 seconds using setTimeout() and then just resolve() after pushing the post instead of callback() .

Now we need to call the function createPost() defined with the post content , which will use .then is used to handle promised response .

reject is used to handle the error related things! and .catch is used to do that.

SO this is essentially all about promises and how they exactly work!

Fetch API:~

It is new standard for HTTP requests other than AJAX where Fetch API actually returns a promise more often.

So to understand it , we can re-create easyhttp library using Fetch API.

This is how Fetch API is used to get TEXT ,JSON and EXTERNAL API.

Arrow Functions:~

Modifying easyhttp with Fetch:~

Modified version of easyhttp :

This is how you can achieve same easyhttp library with FetchAPI and Promises.

Async/Await:~

With this , we add async to the beginning of function , doing that makes any function a compulsion to return a promise, so when we would console it , it would no longer return a string , would eventually return a promise.

Output is :”Hello”

We can have independent async like this without wait.

Doing something asynchronous , we need wait then to actually wait until the function is resolved.

So here we use both async and wait such that we create a new promise inside the function with both parameters and when the function is resolved , wait comes into picture , which will wait for the promise until it actually sends the response.

We can bring layers into it , by handling errors as well.

This can be one of the simple example. Checkout this:

Here we have a function getUsers() with prefix of async , into which we will await response of the fetch call from jsonplaceholder test API .Once we fetch the users from API call and it is resolved , we would get response in JSON format in const data. Once the response in JSON format is stored in data const , we would return data we fetched eventually.

As async would return a promise we would handle the function with .then to console the information of users fetched.

We can apply this to easyhttp custom library as well.

Like the way in Easyhttp classes , we have returned promise in every request method , we are going to turn these functions into async functions .

This is how we have travelled from AJAX to Fetch API to Async/Await to achieve more robustness , modularity , readability and efficient usage of modern ES6.

This is all cut to the chase about Modern JS . The more you would implement projects out of it, the better concepts would get framed.

Happy Learning:-)

Coding empowers magic to my thought with a wing of programming!