Promises sound nice, right (at least better than AJAX which always reminds me of cleaning)? And almost like in real life, JavaScript promises have three states. When a promise is made its state is pending – promise was made, but there was no outcome yet. However in the future (or several miliseconds later) it can become resolved or rejected .
Let’s look at an example
Here we have a basic promise, for which we know it will be resolved, as 1 === 1
is true and we can display the result. But if we change the condition to 1 !== 1
, the promise becomes rejected.
See the Pen Promises – basics by 22nds (@22nds) on CodePen.0
Async events
The beauty of JavaScript promises comes from handling async events, such as downloading and displaying content (text, images, JSON…). Without promises the function which is updating the DOM would be called before we got content, so our placeholder div wouldn’t have any content to display.
See the Pen Promises for Fetch by 22nds (@22nds) on CodePen.0