Do you make Promises?
Now, even though a Promise is an object, it can work as a method. A Promise takes in one single parameter which is a function that will take in two variables, resolve and reject. Those are two results we can have from our Promise. Either the promise is completed which is resolved, or it has failed which is rejected. This means a Promise can be in certain states.
- Pending: Promise is waiting for the operation to be completed
- Fulfiled: The Promise became a success.
- Rejected: The Promise got a result of a failure.
Interacting With Promises.
Now that we have a Promise, you can interact with it.
Two Chaining Methods:
- Then: A function, that takes in a function to be executed when a Promise has been fulfilled.
- Catch: A function, that takes in a function to be executed when a Promise has been rejected.
Here below is an example using these two methods on the Promise that was seen earlier.
You can see in this example that we have chained the then method on the Promise. The method is taking in a function and that function takes in a message parameter and inside the function, it's saying print this message to the console when the Promise is successful. With catch, we have done the same and it takes in a function with a message passing into that function, saying do this action, print this message to the screen when the Promise has been rejected.
We have touched on key things like:
- A Promise is an object that will eventually bring back a value when it is completed.
- A Promise is either in one of the three states, pending, fulfilled, or rejected.
- Can chain methods on to a Promise to do some action and return a value when the operation is done using, Then and Catch methods.