All You Need to Know About JavaScript Promises

One of the most widely used building blocks of the web, JavaScript is a powerful client-side scripting language that predominantly uses single-threaded programming. If a piece of code is being executed, the control wouldn’t be transferred until it finishes its execution. Although this simplifies the code, it has its drawbacks. 

Imagine a function waiting for a resource or performing a network request. This takes time, and meanwhile, the entire execution freezes. 

To overcome this drawback, asynchronous programming comes into play. With the help of features like Callbacks, Promises, and Async/Await, you can perform time-consuming actions without affecting the main execution thread. 

In this article, you’ll be introduced to Promises with the help of a simple demo. 

Full Stack Java Developer Course

The Gateway to Master Web DevelopmentExplore Course
Full Stack Java Developer Course

What Are JavaScript promises? 

A promise is an asynchronous action that may complete at some point in the future and produce a value. This value is not necessarily known at the time of its creation. Once the value is produced, it notifies the user. 

Promises provide a robust way to wrap the result of asynchronous work, overcoming the problem of deeply nested callbacks. 

A JavaScript promise is created with the help of the new keyword. Here’s the general syntax: 

let some_action = new Promise(function(resolve, reject)

{

  // Perform some work

})

The Promise object takes a callback function as a parameter, which, in turn, takes two parameters, resolve and reject. The promise is either fulfilled or rejected. 

There are three states governing promises:

  1. Pending - The promise is pending when it's created. This means that the promise is yet to be fulfilled and the underlying operation is not yet performed. 
  2. Fulfilled - This state indicates that the operation has finished and the promise is fulfilled with a value. 
  3. Rejected - This means that an error occurred during the process and the promise has been denied.

It’s known that if a promise is fulfilled, then some piece of code must be executed. And if it's rejected, then error handling must be performed. So for this, there are two methods: 

1. then(callback) is invoked to attach a callback when the promise is resolved/fulfilled.

.this(function(result){

// handle success } 

2. catch(callback) method is invoked to attach a callback when the promise is rejected. 

.catch(function(error){

//handle error }

Once a promise is settled (either fulfilled or rejected), it's said to be immutable and cannot change its state. 

To help you understand the concept better, see a pictorial representation of promises below: 

promises

    Promises_Workflow - JavaScript Promises

Now that you know what JavaScript promises are and their general syntax, let’s walk through a simple demo. 

<script> 

  let car = new Promise(function(resolve,reject){

fuel_fullTank = true;

           if(fuel_fullTank)

           resolve()

     else

                 reject()

             });

  car.then(function(){

       document.write("The fuel tank is full. Happy Driving!!")

}).catch(function(){

             document.write("The fuel tank is not empty.")

})

</script>

In the above code, we’re checking the car’s fuel. The callback function checks for the full condition on the fuel tank. If it's true, the Promise is fulfilled, and the then() method is invoked. If not, the error is caught by the catch() method. 

Since we’ve hardcoded the value of fuel_fulltank variable to true, the then() method is invoked. 

/fuel-tank.

JavaScript Promises

If the value of the variable fuel_fulltank were set to false, then the output would be as follows: 

fueltank-empty

JavaScript Promises

Nested Promises

Now that you know how promises work, let’s show how nested promises work. 

In this case, the value of a promise depends on the value of other promises. 

Consider a code that checks for the scenario when the fuel tank is empty. If the case is true, then you check if the engine is heating. If this holds as well, you can display a warning message and finally end the promise. 

let empty_tank = function(){

                return new Promise(function(resolve,reject){

                     resolve("The car doesn't have enough fuel.")

                 })

             }

The code above creates a function that returns a promise. This function is assigned to the variable empty_tank, and the promise gets resolved with a message. 

Similarly, here are two more functions, engine and travel, that return a Promise: 

let engine = function(msg){

                 return new Promise(function(resolve,reject){

                     resolve(msg + "The engine is over heating.")

                 })

             }

             let travel = function(msg){

                 return new Promise(function(resolve,reject){

                     resolve(msg + "The car is not safe for driving.")

                 })

             }

To perform the actions, we use the then method. 

empty_tank().then(function(result){

                 return engine(result)

             }).then(function(result){

                 return travel(result)

             }).then(function(result){

                 console.log("Done!" + result)

             })

We first call the empty_tank function, which returns a promise. The then method holds a callback function to check the engine. 

Here, we’ve returned the function engine. The engine function now returns another promise over which the then method is run again. Within the callback function, we’ve returned the last function, travel

Now we run the then method on the promise that’s returned to display a message indicating that all the three promises are resolved. 

Since every promise is displaying a message, we can catch the message as a result and pass the value to the following functions. We’ve also appended the message in the promises. 

When the above code is run, the following output is seen: 

nested-promises

Nested Promises


Get a firm foundation in Java, the most commonly used programming language in software development with the Java Certification Training Course.

Next Steps 

If you wish to learn more about the concept of JavaScript promises, watch the Simplilearn video tutorial, JavaScript Promises Explained.

And if you wish to learn JavaScript, consider a certification course. Simplilearn’s JavaScript Certification Training Course helps you master the JavaScript programming language in an all-inclusive training program that includes complete JavaScript fundamentals, jQuery, Ajax, and more. You’ll apply your skills by building a real-time chat application.

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.