Lang
Blog

Promises in JavaScript- An Introductory Guide

Yes, JavaScript also makes promises.

ByPayal Mittal
January 4th . 5 min read
Promises in JavaScript- An Introductory Guide

JavaScript, being single-threaded, cannot run two pieces of script simultaneously, one will have to wait for another to complete then only it can run. But by using Callback functions, it manages these asynchronous operations.

But over the years, Promises replaced Callback functions and are now considered as the most prominent method to handle the results of async operations that haven’t completed yet.

In this blog, we’ll understand the concept of Promises in better terms. So, let’s get going-

What’s a Promise in JavaScript?

There are several analogies in JavaScript that must be addressed here -

  • Producing code: A producing code that results in output over time.
  • Consuming code: A consuming code wants the result of the producing code.

A promise bonds these two analogies, by promising each one something; that is, the producing code will take whatever time it needs to come out with the promised results, while the consuming code will have its results when it’s ready.

A Promise is an object representing the eventual completion or failure of an asynchronous operation.

A Promise is a means of assurance that a particular operation will occur in the near future. Though, it is not necessary that the promise will be fulfilled every time.

Whenever a particular condition is true, the promise will work and when it’s not, it will not. As simple as that!

Promise vs Callback

When an asynchronous action triggers, one of these two concepts is used to handle its results. While the purpose is behind both Callback and Promise is the same, they work differently.

Essentially, a promise is a returned object you attach callbacks to, instead of passing callbacks into a function.

A Callback function is passed as an argument in another function, we often use these Callback functions in setInterval functions, in API calls, event listening, etc. These functions are defined somewhere in the code and are called back in another function to notify JavaScript that a certain asynchronous activity has been completed.

These callbacks make sure that our code will not run before the asynchronous task but will run right after it finishes.

But this approach is fruitful only in the short asynchronous operations, but when it comes to large sets, it is not the best practice to use. Thus, came Promises!!

Promises are more flexible and can be used for large sets of async operations.

However, the major difference between Callback and Promises is that promise-based APIs return a promise that is used to declare a function in then() and catch(), which further determines what will happen once the async operation has completed. On the other hand, the Callback-based APIs do not return any value, they just carry out the Callback with the result.

However, the interesting fact, here, is that we still use callbacks in promises.

How does a Promise work?

A promise follows a very simple concept, very much like it works in real life. It promises to do something in the future.

It has two possible outcomes: it will either be kept or it won’t. Once we define a promise in JavaScript, it will either be resolved when the time comes or will get rejected.

A Promise return one of these 3 possible states:

  • pending: initial state, when the promise has neither fulfilled nor rejected.
  • fulfilled: Promise resolved successfully.
  • rejected: Promise failed.

For instance, when a Promise is created to deliver some data, it will stay in pending mode until we get our data. If we receive the promised data, the promise will be in resolved state and if we don’t, it will return to rejected state.

Basic Syntax -

This is the basic syntax for creating a new Promise-

let myPromise = new Promise(function(myResolve, myReject) {
 
   myResolve(); // when successful
   myReject();  // when error
 });

A promise handles the asynchronous results of an operation and notifies when it’s done. The concept is similar to callbacks but the approach is different.

Flow of then() and catch()

Once a promise is handled, whether it got resolved or failed, the next step is to deal with the results. Here comes two methods; .then() and .catch().

promises-in-javascript-an-introductory-guide_1.jpg

then() is used to pass a function argument which will be run after a promise calls resolve() and catch() after it calls reject().

myPromise.then((message) => { 
    console.log(message);
}).catch((message) => { 
    console.log(message);
});

Here’s the catch -

You can use then() to make two arguments, first to handle the resolve() case and second to handle the reject() case.

promise.then(
  function(result) { /* handle a successful result */ },
  function(error) { /* handle an error */ }
);

But if you’re interested more in success cases, you can pass a single argument in then() and if you’re interested only in errors, you can use catch() for error handling.

Furthermore, they are chained as they return a Promise and the process goes on.

One of the most important benefits of promises is that they handle a chain of events better than callbacks through Chaining. While using callbacks in a conventional way creates ‘Callback Hell’, chaining is an effective method where we chain promises and callbacks together.

Wrap Up:

This was a brief look into the Promises in JavaScript. However, there is more to learn, this was all but a small picture. When you get into a broader perspective, the topic becomes more complex.

But once you have a basic understanding, it will be easier for you to get into the details. Hopefully, this blog polished your basic understanding of JavaScript Promises and Callbacks.

Thanks for reading.

If you need any help regarding your JavaScript project, feel free to contact out subject experts at HabileLabs.

Keep in touch with us and continue reading for further blog updates

Share:
0
+0