different ways to make an HTTP request in JavaScript

[1]. Ajax (XMLHttpRequest)

[2]. jQuery’s $.ajax() > $.post(), $.get(), $.getJSON(), $.load()

[3]. Fetch API (modern) over XHR (traditional)

[4]. Axios (open source library)

[5]. Angular HttpClient

[1]. Ajax

Ajax is the traditional way to make an asynchronous HTTP request. Data can be sent using the HTTP POST method and received using the HTTP GET method.

To make an HTTP call in Ajax, you need to initialize a new XMLHttpRequest() method, specify the URL endpoint and HTTP method (in this case GET). Finally, we use the open() method to tie the HTTP method and URL endpoint together and call the send() method to fire off the request.

For years, XMLHttpRequest has been web developers’ trusted sidekick. Whether directly or under the hood, XMLHttpRequest has enabled Ajax and a whole new type of interactive experience, from Gmail to Facebook.

However, XMLHttpRequest is slowly being superseded by the Fetch API. Both can be used to make network requests, but the Fetch API is Promise-based, which enables a cleaner, more concise syntax and helps keep you out of callback hell.

Regarding the Ajax requests, the Fetch API, or alternatively, the Axios library, are now more popular tools for performing asynchronous operations. That said, jQuery is still very much alive and powers almost 70,000 websites worldwide.

Ajax is a technology that allows developers to make asynchronous HTTP requests without the need for a full page refresh.

[2]. jQuery methods

jQuery has many methods to easily handle HTTP requests. In order to use these methods, you’ll need to include the jQuery library in your project.

<script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Some of jQuery’s most-used Ajax shorthand methods: $.get(), $.post(), $.getJSON and $.load(). They are convenient methods for making Ajax requests in a few lines of code. But sometimes, we need more control over the Ajax calls we want to make.

jQuery has all these above methods to request for or post data to a remote server. But you can actually put all these methods into one: the $.ajax method

For example, we want to specify what should happen in case an Ajax call fails or we need to perform an Ajax request but its result is only needed if retrieved within a certain amount of time. In such situations, we can rely on another function provided by jQuery, called $.ajax(), that is the topic of this tutorial.

$.ajax() Function

The jQuery $.ajax() function is used to perform an asynchronous HTTP request. It was added to the library a long time ago, existing since version 1.0. The $.ajax() function is what every function (discussed in $.get(), $.post(), and $.load()) calls behind the scene using a preset configuration.

$('#action-button').click(function() {
$.ajax({
url: 'https://api.joind.in/v2.1/talks/10889',
data: {
format: 'json'
},
error: function() {
$('#info').html('<p>An error has occurred</p>');
},
dataType: 'jsonp',
success: function(data) {
var $title = $('<h1>').text(data.talks[0].talk_title);
var $description = $('<p>').text(data.talks[0].talk_description);
$('#info')
.append($title)
.append($description);
},
type: 'GET'
});
});

They do what they say they do.

  • $.ajax is the function used to send XMLHttpRequests
  • $.post is a POST wrapper for $.ajax
  • $.get is a GET wrapper for $.ajax
  • $.load is the same concept, but allows you to load the content into a selected element easily.

[3]. Fetch API

The Fetch API provides a inbuilt fetch() method defined on the window object, which you can use to perform requests. This method returns a Promise that you can use to retrieve the response of the request.

The fetch method only has one mandatory argument, which is the URL of the resource you wish to fetch.

fetch(url, {options});   //{options} is optional in case of 'GET'
  • If its a GET request, no need to mention in {optionals} but is very much required in POST & others http verbs.

A very basic example would look something like the following. This fetches the top five posts from r/javascript on Reddit:

fetch('https://www.reddit.com/r/javascript/top/.json?limit=5')
.then(res => console.log(res));

If you inspect the response in your browser’s console, you should see a Response object with several properties:

{
body: ReadableStream
bodyUsed: false
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: ""
type: "cors"
url: "https://www.reddit.com/top/.json?count=5"
}

It seems that the request was successful, but where are our top five posts? Let’s find out.

We can’t block the user interface waiting until the request finishes. That’s why fetch() returns a Promise, an object which represents a future result. In the above example, we’re using the then method to wait for the server’s response and log it to the console.

Now let’s see how we can extract the JSON payload from that response once the request completes:

fetch('https://www.reddit.com/r/javascript/top/.json?limit=5')
.then(res => res.json()) //here, json() returns a promise
.then(json => console.log(json));

We start the request by calling fetch(). When the promise is fulfilled, it returns a Response object, which exposes a json method. Within the first then() we can call this json method to return the response body as JSON.

However, the json method also returns a promise, which means we need to chain on another then(), before the JSON response is logged to the console.

And why does json() return a promise? Because HTTP allows you to stream content to the client chunk by chunk, so even if the browser receives a response from the server, the content body might not all be there yet!

Another example:

[4]. Axios

Axios is an (3rd party) open source library for making HTTP requests and provides many great features. Let’s have a look at how it works.

Usage:

First, you’d need to include axios. There are two ways to include axios in your project.

First, you can use npm:

npm install axios --save

Then you’d need to import it

import axios from 'axios'

Second, you can include axios using a CDN.

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

With Axios you can use GET and POST to retrieve and post data from the server. axios takes one mandatory parameter url, and can take a second [optional] parameter too.

POST:

Axios returns a “Promise.” If you’re familiar with promises, you probably know that a promise can execute multiple requests. You can do the same thing with axios and run multiple requests at the same time.

Axios supports many other methods and options. You can explore them here.

Difference between Fetch() & axios

Expected data can be retrieved via fetch() using two steps (or two .then()) whereas axios already returns the stringified result, so only one .then() is required.

[5]. Angular ‘HttpClient’

Angular has its own HTTP module that works with Angular apps. It uses the RxJS library to handle asynchronous requests and provides many options to perform the HTTP requests.

Wrapping Up

We’ve just covered the most popular ways to make an HTTP call request in JavaScript.

Thank you for your time.

◉ Async … await

The .then() syntax is nice, but a more concise way to process promises in 2018 is using async … await — a new syntax introduced by ES2017. Using async & await means that we can mark a function as async, then wait for the promise to complete with the await keyword, and access the result as a normal object. Async functions are supported in all modern browsers (not IE or Opera Mini) and Node.js 7.6+.

Hence, async-await offers a different syntax for writing Promises that some find clearer. With async-await, you can create an async function. Within that async function, you can await the result of a Promise before executing subsequent code!

async function fetchTopFive(sub) {
const URL = `https://www.reddit.com/r/${sub}/top/.json?limit=5`;
const fetchResult = fetch(URL)
const response = await fetchResult;
const jsonData = await response.json();
console.log(jsonData);
}

fetchTopFive('javascript');
Why Async/Await
async function getPromise() {
const data = await getData();
}

The purpose of async/await functions is to simplify the behaviour of using Promises synchronously and to perform some behaviour on a group of Promises. Just as Promises are similar to structured callbacks, one can say that async/await is similar to combining generators and Promises.

Only inside a function marked as async, you are allowed to place the await keyword in front of an expression that returns a Promise. When you do, the execution is paused until the Promise is resolved.

Being that it was built on top of Promises, you could simply see it as a new way of writing synchronous code.

Just like Promises themselves, async/await is equally non-blocking.

Let’s look at our data fetch example.

Pretty nice, right? One small wrinkle: we’re not handling our Promise rejection case. We can do this with try/catch.

Putting the keyword “async” before a function tells the function to return a Promise. If the code returns something that is NOT a Promise, then JavaScript automatically wraps it into a resolved promise with that value e.g when it returns an AsyncFunction object:

The await keyword simply makes JavaScript wait until that Promise settles and then returns its result:

Note that the await keyword only works inside async functions, otherwise you would get a SyntaxError.

Advantages of Async / Await :-

  1. Error handling
  2. Conditionals
  3. Chaining
  4. Error reporting
  5. Lower memory requirements
  6. Neat syntax

The fundamental difference between await and vanilla Promises is that await X() suspends execution of the current function, while promise.then(X) continues execution of the current function after adding the X call to the callback chain. In the context of stack traces, this difference is pretty significant.

All you need to know about JavaScript Async Await

source: https://medium.com/@mayank.gupta.6.88/javascript-async-await-c83b15950a71

Returning Promises with Async Keyword

When we append the keyword “async” to the function, this function returns the Promise by default on execution. Async keyword provides extra information to the user of the function:

  1. The function contains some Asynchronous Execution
  2. The returned value will be the Resolved Value for the Promise.

Let’s validate it with a small example.

The output from the above execution returns an already resolved promise.

In the above code, since the value returned is a promise, we can capture the promise and extract value from the same. We can associate a callback function with the promise using “then

Let’s see the above code in action…

To in order to summarize the impact of the “Async” keyword, we can state:

  1. Appending “async” will return a promise from a function
  2. In case the function is returning some value, the value will be available as the resolved value from the promise.
  3. If no value is returned, the resolved value will be “undefined”

Understanding Asynchronous Execution

Working with realtime scenarios, we might have some functions which return a promise on its execution. The promise returned from the function might resolve after some time, meanwhile, the main executing thread does not wait for the promise to be resolved, it proceeds further execution of the synchronous part of the application. Once the promise is resolved, its callback function is executed.

Let’s look for the below code to understand the behavior.

The output for the above execution gives you the following output:

In the above code, we need to observe the following points:

  1. Value “Mayank” is displayed before “Promise Executed”
  2. Promises are asynchronous and waiting on other thread for completion
  3. JavaScript does not wait for the promise to resolve, it executes further
  4. Once the promise is resolved the callback function is invoked.

Working with the “await” keyword

Adding “await” before a promise makes the execution thread to wait for asynchronous task/promise to resolve before proceeding further. When we are adding the “await” keyword, we are introducing synchronous behavior to the application. Even the promises will be executed synchronously. Lets’s update the code above to replicate synchronous behavior.

In the above code, the following points need to be kept in mind:

  1. “returnPromise()” returns a Promise which needs to wait at least for 3 seconds before getting resolved.
  2. We have updated the “await” keyword in front of the function call, which forces the promise to be resolved before the code is executed further
  3. After a delay of 3 seconds, the promise will be resolved and the further execution of the code will resume. It introduces synchronous behavior
  4. “async” keyword needs to be updated in front of functions that contain ”await” keyword to notify that the result might be available after a certain delay since we are explicitly making the main thread wait until the promise has been resolved.
  5. Await and Async has introduced synchronous behavior to the Execution.

Conclusion:-

Await and Async keyword combined together ensures that the main thread will not start executing further until the asynchronous part of the application has finished execution hence imparting synchronous behavior to the thread.

Why is async,await needed when Promises does similar job? Does async,await solve a bigger problem?

async/await simply gives you a synchronous feel to asynchronous code. It's a very elegant form of syntactical sugar.

For simple queries and data manipulation, Promises can be simple, but if you run into scenarios where there’s complex data manipulation and whatnot involved, it’s easier to understand what’s going on if the code simply looks as though it’s synchronous (to put it another way, syntax in and of itself is a form of “incidental complexity” that async/await can get around).

The first things you have to understand that async/await syntax is just syntactic sugar which is meant to augment promises. In fact the return value of an async function is a promise. async/await syntax gives us the possibility of writing asynchronous in a synchronous manner. Here is an example:

Promise chaining:

function logFetch(url) {
return fetch(url)
.then(response => response.text())
.then(text => {
console.log(text);
}).catch(err => {
console.error('fetch failed', err);
});
}

Async function:

async function logFetch(url) {
try {
const response = await fetch(url);
console.log(await response.text());
}
catch (err) {
console.log('fetch failed', err);
}
}

In the above example the await waits for the promise (fetch(url)) to be either resolved or rejected. If the promise is resolved the value is stored in the response variable, and if the promise is rejected it would throw an error and thus enter the catch block.

We can already see that using async/await might be more readable than promise chaining. This is especially true when the amount of promises which we are using increases. Both Promise chaining and async/await solve the problem of callback hell and which method you choose is matter of personal preference.

Experience with Front-end Technologies and MERN / MEAN Stack. Working on all Major UI Frameworks like React, Angular.