Promises in javascript!

Promises in javascript!

ยท

2 min read

Table of contents

No heading

No headings in the article.

According to MDN, a promise is an object representing the eventual completion or failure of an asynchronous operation.

Promises are used to deal with asynchronous operations in javascript.
An asynchronous operation can be like, getting data from Netflix API. So when we request the data from Netflix API we don't know when that data we will get ๐Ÿค”? or how much time it will take โŒ›? but whenever we have that data/response back in our javascript code, we want to run some code on it, for that we can use promises.

Let's understand this with the help of a fetch example:
Whenever we make a network request using fetch(URL), two things happen:

  1. It returns a placeholder object(promise) immediately in javascript.
  2. Initiates background web browser work for completing the request.

So whenever the request is completed the data which we have from the server will go into our promise object.

p1.JPG

onFulfillment and onRejection are linked with the background work happening in the web browser. On completion of the request data which is received from the server is stored in the value property.
So we need some code to run automatically on that data to use it. For that when the value property is updated, the functions present in onFulfillment array will be executed automatically by javascript.
But to get functions inside that array we can't do onFulfillment.push(someFunction) because onFulfillment is the hidden property and we don't have access to it. So for that we have .then(someFunction) which will put the function in that onFulfillment array.

fetch("http://api.netflix.com")
.then((data) => {
      // console logs the data i.e response from the Netflix api
     console.log(data)
)

Promise object will automatically trigger the functions which are in onFulfillment array with an argument data which is received from the server.

Now this will happen when we receive our response i.e data from the server, but if anything goes wrong we will have an error, so to handle that error, there is another property in the promise object called as onRejection which is an array.

Functions inside onRejection array will be triggered when error occurs. To put functions inside that array the are two ways:

  1. Second argument to .then i.e .then(someFunction, errorHandlingFunction)
  2. .catch(errorHandlingFunction)
fetch("http://api.netflix.com")
.then((data) => {
     console.log("You get the data from Netflix ๐Ÿ˜Ž")
). catch((error) => {
     console.log("Error occurred ๐Ÿ™„")
})

All these functions in onFulfillment or onRejection array for execution will go through the microtask queue. Microtask queue has higher priority so callbacks in the microtask queue will be executed first.

References: MDN, Frontend Masters

ย