Promises in JavaScript
A Promise in JavaScript is an object. Its purpose is to represent the eventual completion or failure of an asynchronous operation. In saying that promises have three states:
Pending: Initial state the operation isn’t complete and therefore neither resolved nor rejected.
Fulfilled: The operation was successfully resolved.
Rejected: The operation failed.
If a promise is resolved it will run .then that follows it on the other hand if the promise is rejected it will run the .catch that follows it. Here is an example of a promise that will randomly either be rejected or fulfilled:
This isn’t a practical example it's just simply to show a promise and what it is. A set timeout is placed in so our promise will be pending for 3 seconds before it is resolved or rejected like an actual promise might be. (This is valid code just not useful).
While coding and learning to code in JavaScript I haven’t used a promise in this context where I would simply create a new promise and then add some operations to it. However, promises very important and I have used promises often without creating a new promise in this way. One of the most common uses is with fetch or axios when collecting data from a backend or an external API these return a promise that will be either fulfilled or rejected. Furthermore, we can use .then to return a promise and chain promises together linearly without nesting and the .then would run after each promise is resolved. Chaining promises with .then we would only need one .catch to catch a rejected promise and we could place this after the .then.
The Modern Javascript Bootcamp Course (2021) clearly explains and was helpful for me in understanding promises in JavaScript.