Sign in
Log inSign up
Understanding Asynchronous operation, Promise & Fetch Call in JavaScript.

Understanding Asynchronous operation, Promise & Fetch Call in JavaScript.

Atul Patil's photo
Atul Patil
·Oct 28, 2021·

4 min read

What is a Promise?

promisese.png Before Understanding promise you should know difference between Asynchronous and Synchronous nature of JavaScript.

Synchronous Programming - In this programming/operation the task are performed one at a time & only when one is completed the following will execute. In simple words you need to wait for a task to finish to move to next one.

Asynchronous Programming - In this operation you can move to another task even if the previous task execution is not finished. This way you are able to deal with multiple task simultaneously, thus completing more task in shorter period of time. Fetching, Promises these are the example of Asynchronous Programming.

Promises - Now lets understand promises, It is nothing but an a object which is used to handle Asynchronous operation like network calls. A promise is a proxy for value not necessary known when the promise is created. Instead of immediately returning the final value, the async method returns the a promise. Whoa, If you are having trouble understanding this then don't worry let me explain you this is simple term with an example, So whenever you click on Instagram story of your friend, that story loads(that ring around profile picture), means you are requesting for the data from the server, till the data fully fetch you can scroll on the Instagram because of Async operation, Once the data is fetch you can see uploaded story of your friend. here you can see the fetch call execute a promise which says that "you can go ahead with the execution & don't wait for me, I'll let you know once I get the data" This is extremely important in browsers, you don't want your users not to be able to click on something, or everything to stop when browser is getting data.

A Promise returns 4 states which are as follows

  1. Pending : Initial state, Neither fulfilled nor rejected.
  2. Fulfilled : Operation is completed successfully.
  3. Rejected : Meaning that the operation is failed.
  4. Settled : The promise has either fulfilled or rejected.

rywxmm88tzejejqhr8pg.png

const promise = new Promise((resolve, reject) => {
 // this code will run if the promise resolved or reject, 
 // The resolve and reject are the callback function 
 // also called as executor function works as a parameter
});

Response, Fetch API and Error Handling

.then() & .catch- Now we know what promise is, next step is handling the response of the fetch request, It can be fulfilled or rejected. So for that we have to right code accordingly.

.then() is used to handle success and .catch is use to handle failure or errors of the promise respectively. both take the callback function which consume the response of the fetch request.

const url = "quick-access-api.desaihetav.repl.co" 
 fetch(url)
.then(response => response.json())
.then(json => console.log(json))
.catch(error => console.log("Error"))

In the above program you can see that we have passed the URL from fetch(), here fetching is nothing but requesting for data from server, If the promise is successful then as we discuss earlier the .then() will consume the callback function response => response.json(), here in this callback, response we get from fetch call is acts as a parameter. we are requesting to convert data into json format, But even if the function contains json() the data is still not converted into JSON, So for that we have to use another .then() , this is because the response that we got from callback function is not suitable for our use, We need to convert that into proper object Notation that is JSON format.

Why JSON? - JSON is JavaScript object notation, it is used to transfer data from server to the web page, It is light weight format for storing and transportation of data, It converts the complex JavaScript code into objects so that we can access those object easily.

Now, when we called .json() this method also returns a Promise. So now do the same thing again i.e. call .then() method for handling success of this new Promise.

We don't have to write .catch() for both the .then(), writing for one is enough. By this we can chain the number of promises one after another still the code will be executed. This is the advantage of promise.

I hope now you will not face trouble explaining someone about Promises and Fetch Call. Thanks for reading, You can connect me on Twitter

Hassle-free blogging platform that developers and teams love.
  • Docs by Hashnode
    New
  • Blogs
  • AI Markdown Editor
  • GraphQL APIs
  • Open source Starter-kit

© Hashnode 2024 — LinearBytes Inc.

Privacy PolicyTermsCode of Conduct