What states can a promise be in, and how do you move between them?
A promise begins in the pending state. Later it settles, and settling means moving to exactly one of two final states. It becomes fulfilled when it is resolved with a value, and it becomes rejected when it is rejected with a reason. Once a promise has settled, it stays in that state for the rest of its life.
const promise = new Promise(function (resolve, reject) {
resolve('done');
});
promise.then(function (value) {
console.log('fulfilled:', value);
});
promise.catch(function (err) {
console.log('rejected:', err.message);
});
// A rejected promise.
const failing = new Promise(function (resolve, reject) {
reject(new Error('boom'));
});
failing.catch(function (err) {
console.log('caught:', err.message);
});
The executor function runs straight away, without waiting, at the moment the promise is created. That means any code before the first await is not really asynchronous, and a long calculation inside the executor blocks the thread exactly like any other code.
You watch the states with the then method, which takes a success handler and an optional failure handler, and with the catch method, which is simply then with the success handler left out. There is also a finally method, which runs its callback no matter what happened. That is the right place for cleanup work such as hiding a loading spinner.
Two details about the handlers are worth knowing. The success handler receives the resolved value, but if that value is itself a promise, the promise machinery waits for it and hands you the inner value instead. People call that unwrapping. The second detail is that handlers registered with then never run immediately. They are queued as microtasks, so even a promise that has already settled calls its handler a little later.