A promise can be in one of three states. When created, a promise is pending, and then it can become fulfilled, returning the result, or rejected, returning the reason for the failure. You can watch the transition from one state to another by running the following code:
let promise = new Promise(function(resolve, reject) {
setTimeout(function() {
let isError = false; // set either true or false
if (!isError) {
resolve([1, 2, 3, 4, 5]);
} else {
reject('an error in promise');
}
}, 3000);
});
setInterval(function() {
console.log(promise); // we output a promise to the console every second
}, 1000);
Keep in mind that the states fulfilled and rejected are immutable: once a promise has gone into one of these states, it will no longer be able to go into the other. Let's look at an example. In the following code, the call to reject will happen first, so the call to resolve will be ignored:
let promise = new Promise(function(resolve, reject) {
setTimeout(() => reject(new Error('error')), 1000);
setTimeout(() => resolve('ignored'), 2000);
});
Make a promise that will succeed after some time. Print it to the console and examine its initial state and completed state.
Make a promise that will fail after some time. Print it to the console and examine its initial state and completed state.