A brief introduction about Asynchronicity in JavaScript Part two

Posted By : Kamal Yadav | 30-Jul-2019

In this blog, we will continue to understand the asynchronous behavior of JavaScript. Other than callback, javascript provides us with some better methods to handle asynchronous code. One of them is Promises.

Now, Let's go over some basic concepts about promises. A promise is simply an object that tells us about the completion or failure of an asynchronous task and the value it results.
Promises are the ideal choice for handling asynchronous operations in an easy way. They are able to handle multiple asynchronous operations easily and provide better error handling than callbacks.

A Promise can have four states:
fulfilled: Action related to the promise succeeded.
rejected: Action related to the promise failed
pending: Promise is still pending i.e; it has not fulfilled or rejected yet.
settled: Promise has fulfilled or rejected(some action has been performed).

The syntax for writing Promises is as follow:

var newPromise = new Promise(function(resolve, reject){ //write your code here });

Parameters that promise take: Promise constructor takes only one argument, a callback function. The callback function takes two arguments, resolve and reject Operations are performed inside the callback function and if everything went well then call resolve.

Basic Example:

var promise = new Promise(function(resolve, reject)

{ const x = "Hello";

const y = "Hello"

if(x === y)

{ resolve(); }

else { reject(); } });

promise. then(function () { console.log('Success, Promise got resolved'); }). catch(function () { console.log('Error '); });

So, here we created a new promise and then simply checked if two values are equal, then resolve the promise, else reject it.

Now, if the promise got resolved successfully, the code will go inside the "then" function else the code will go in the "catch" function, in case any error occurs.

In the above example, the code will go in the "then" function, as the value we have provided is equal, which will result in resolving the promise. So, the resulting output, in this case, will be "Success, Promise got resolved".

Now suppose in the above example, if the values provided would not have been equal, then the promise would have gone in the rejected state and catch function will be called. And the catch console would have been printed "Error".

This is the basic idea for working with Promises.

About Author

Author Image
Kamal Yadav

Kamal is an associate developer with good logical skills. He has good knowledge of JavaScript.

Request for Proposal

Name is required

Comment is required

Sending message..