A promise in JavaScript is an object that represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.
Promises provide a way to register callbacks to be called when the asynchronous operation completes, and can simplify the handling of asynchronous code.
They can be in one of three states: fulfilled, rejected, or pending. A promise is said to be “settled” if it is either fulfilled or rejected, and “unsettled” if it is pending.
Here is an example of using a promise to handle the completion of an asynchronous operation:
const myAsyncFunction = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Hello, World!');
}, 1000);
});
};
myAsyncFunction()
.then(result => {
console.log(result); // 'Hello, World!'
})
.catch(error => {
console.log(error);
});
In this example, myAsyncFunction returns a new promise. The promise is created with a constructor that takes a single argument, a function called the “executor”. The executor is called immediately when the promise is created. The executor takes two arguments, a function called resolve, and a function called reject.
The setTimeout function is used to simulate an asynchronous operation that takes 1 second to complete. When the timeout expires, the resolve function is called with the string “Hello, World!” as an argument. This causes the promise to be fulfilled with the value “Hello, World!”.
The then method is used to register a callback that will be called when the promise is fulfilled. The callback is passed the fulfilled value as an argument. The catch method is used to register a callback that will be called if the promise is rejected.