Lesson 5 of 20By Simplilearn
Last updated on Jun 26, 20202128One 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.
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:
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_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.
JavaScript Promises
If the value of the variable fuel_fulltank were set to false, then the output would be as follows:
JavaScript 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
Get a firm foundation in Java, the most commonly used programming language in software development with the Java Certification Training Course.
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.
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.
Full Stack Java Developer
*Lifetime access to high-quality, self-paced e-learning content.
The Best Guide to Understanding JavaScript Learning Path
Free eBook: Quality Management Professionals Salary Report
jQuery vs JavaScript: Know The Differences and Similarities Between Them
An Introduction to JavaScript: Here Is All You Need to Know
The Best Guide on How to Implement JavaScript Closures
Free eBook: 2016 High Paying Certifications