JavaScript Promises is a powerful feature for managing asynchronous operations. Promises provide a clean and organized way to handle asynchronous code by representing the eventual completion or failure of an operation.
The syntax for creating and using JavaScript Promises follows a specific pattern. Here’s the syntax for working with Promises:
1. Creating a Promise:
const myPromise = new Promise((resolve, reject) => {
// Asynchronous operation
// If successful, call resolve(value)
// If failed, call reject(error)
});
The Promise constructor takes an executor function as its argument, which receives two parameters: resolve
and reject
. Inside the executor function, you perform the asynchronous operation and call resolve(value)
if it succeeds, or reject(error)
if it fails.
2. Handling Promise fulfillment and rejection:
myPromise
.then((value) => {
// Handle fulfillment
// Access the fulfilled value via the 'value' parameter
})
.catch((error) => {
// Handle rejection
// Access the rejection reason via the 'error' parameter
});
The then()
method is used to handle the fulfillment of the Promise, and the catch()
method is used to handle the rejection. You can chain multiple then()
methods to perform sequential operations. The fulfillment value is accessible in the then()
callback via the value
parameter, and the rejection reason is accessible in the catch()
callback via the error
parameter.
3. Adding a finally
block (optional):
myPromise
.then((value) => {
// Handle fulfillment
})
.catch((error) => {
// Handle rejection
})
.finally(() => {
// Perform cleanup or final tasks
});
The finally()
method allows you to add a callback that will be executed regardless of whether the Promise is fulfilled or rejected. It is optional and is commonly used for performing cleanup operations or final tasks.
JavaScript Promises example
Simple example code.
// Example asynchronous functions
function fetchUserData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const user = { id: 1, name: 'John Doe' };
// Simulating a successful API request
resolve(user);
}, 2000);
});
}
function getUserPosts(userId) {
return new Promise((resolve, reject) => {
setTimeout(() => {
const posts = [
{ id: 1, title: 'Post 1' },
{ id: 2, title: 'Post 2' },
{ id: 3, title: 'Post 3' }
];
// Simulating a successful API request
resolve(posts);
}, 1500);
});
}
// Usage of Promises
fetchUserData()
.then((user) => {
console.log('User data:', user);
return getUserPosts(user.id); // Chaining another asynchronous operation
})
.then((posts) => {
console.log('User posts:', posts);
// Perform further operations with the posts
})
.catch((error) => {
console.log('Error:', error);
});
Output:
Promise Object Properties
Here’s a tabular format listing the properties of the Promise object in JavaScript:
Property | Description |
---|---|
Promise.prototype | Represents the prototype for the Promise constructor function. |
Promise.prototype.constructor | Refers to the constructor function that creates an instance of a Promise object. |
Promise.prototype.then | Represents the built-in then method of the Promise object. |
Promise.prototype.catch | Represents the built-in catch method of the Promise object. |
Promise.prototype.finally | Represents the built-in finally method of the Promise object. |
Promise.resolve | Represents the static resolve method of the Promise object. It returns a resolved promise with a specified value. |
Promise.reject | Represents the static reject method of the Promise object. It returns a rejected promise with a specified reason. |
Do comment if you have any doubts or suggestions on this Js code.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version