- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What are Promises in JavaScript?
Promises, in JavaScript, can be used to simplify asynchronous programming, making it easier to handle asynchronous operations like I/O operations or communicate with an external system or machine. Promises are objects that represent the eventual completion or failure of an asynchronous operation and its resulting value. They provide an easy way to deal with asynchronous code, allowing us to write cleaner and more readable code. Here we will discover what are promises in javascript and how to use them to incorporate asynchronous programming behaviour into our control flow, in this tutorial.
A promise has 3 states −
Pending − The initial state before the promise is resolved or rejected.
Fulfilled − The state representing the successful completion of the asynchronous operation, resulting in a value.
Rejected − The state representing the failure of the asynchronous operation, resulting in an error.
Let’s look at some of the examples to understand the concept better −
Example 1 - Using .then/.catch Syntax
In this example, we will −
create a performAsyncTask() function that returns a promise.
Inside the promise's body, we will create an asynchronous task that resolves the promise with a random number if the number is greater than 0.5. Otherwise, it rejects the promise with an error message.
Filename - index.html
<html> <head> <title>What are Promises in JavaScript?</title> <script> function performAsyncTask() { return new Promise((resolve, reject) => { setTimeout(() => { const randomNumber = Math.random(); if (randomNumber > 0.5) { resolve(randomNumber); } else { reject("Failed to perform the task."); } }, 2000); }); } performAsyncTask() .then((result) => { console.log("Task completed successfully. Result: " + result); }) .catch((error) => { console.log("Task failed. Error: " + error); }); </script> </head> <body> <h1>What are Promises in JavaScript?</h1> </body> </html>
Output
The result will like the image below.
Example 2 - Using async/await Syntax
In this example, we will −
create a fetchData() function that returns a promise.
Inside the promise's body, we will create an asynchronous task that resolves the promise with an object containing sample data after a 2−second delay.
Filename - index.html
<html> <head> <title>What are Promises in JavaScript?</title> <script> function fetchData() { return new Promise((resolve) => { setTimeout(() => { resolve({ data: "Sample data" }); }, 2000); }); } async function getData() { try { const result = await fetchData(); console.log("Data: ", result.data); } catch (error) { console.log("Error: ", error); } } getData(); </script> </head> <body> <h1>What are Promises in JavaScript?</h1> </body> </html>
Output
The result will like the image below.
Conclusion
In conclusion, promises are an important feature in JavaScript that simplifies asynchronous programming. They are objects that represent the eventual completion or failure of an asynchronous operation and its resulting value. We learned what are promises in javascript using different methods and saw some examples explaining the same.