In JavaScript, a promise is an object representing the eventual completion or failure of an asynchronous operation. It is a way to handle
asynchronous operations more elegantly and avoid the "callback hell".
A promise can be in one of three states:
- Pending: The initial state of a promise. It represents that the asynchronous operation is still ongoing and has not yet been fulfilled or
rejected.
- Fulfilled: The state of a promise when the asynchronous operation has been successfully completed. It represents that the promised value is
available and can be consumed.
- Rejected: The state of a promise when the asynchronous operation encounters an error or fails to complete. It represents that an error has
occurred and the promised value is not available.
The basic syntax for creating a promise in JavaScript is as follows:
const myPromise = new Promise((resolve, reject) => {
// Asynchronous operation
// If the operation is successful, call resolve(value)
// If the operation fails, call reject(error)
});
However, when it comes to immediately resolving or rejecting states, creating a new promise with the Promise
constructor and manually
calling resolve
or reject
makes the code verbose and more difficult to read.
const result = new Promise(resolve => resolve(42)); // Noncompliant: Redundant to explicitly create a promise to resolve 42
result.then(value => {
console.log(value); // Output: 42
});
Instead, a promise can be created with Promise.resolve
. It is typically used when you want to create a new promise that is already
resolved with a certain value. It is commonly used to wrap synchronous values or functions into promises.