In JavaScript, a Promise is an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value. It is a container that promises to eventually have a value. Promises are used to handle asynchronous operations in JavaScript. Instead of passing callbacks into a function, a promise is a returned object to which you attach callbacks. Promises have four states: pending, fulfilled, rejected, and settled. The Promise object supports two properties: state and result.
Promises have three methods that are used to associate further action with a promise that becomes settled: then()
, catch()
, and finally()
. These methods return promises, so they can be chained. The then()
method takes up to two arguments: the first argument is a callback function for the fulfilled case of the promise, and the second argument is a callback function for the rejected case. The catch()
method is used to handle rejected promises. The finally()
method is used to run code after a promise is settled, whether it was fulfilled or rejected.
Promises are a very powerful feature that help you run multiple asynchronous operations where they are easy to manage.