When you make a Promise, you define a process which you need to execute and the success/failure case of that process. This is the only parameter of the Promise constructor, an “executor” function that takes two functions: “Resolve” (sometimes called “Fulfill”) and “Reject”. After you’ve instantiated a promise, the executor function will run and the status of the promise will be ‘Pending’ until either Resolve or Reject is executed. After you’ve instantiated a promise, the executor function will run and the status of the promise will be ‘Pending’ until either Resolve or Reject is executed. It looks like this:
Promises help us avoid callback hell (which you can read about at http://callbackhell.com/) and we can then chain on many promises with the .then() method. Each task that’s being chained can only start as soon as the previous task has completed, controlled by the
.thens of the chain. This chain is set up to allow the callback functions to return a promise. Anything returned from the then method either becomes a resolved promise or a rejected promise that will be handled by a .catch block. The then() method is especially useful when fetching data which is what we learned this week.
Using the fetch() method provides us an easy way to gather resources and data asynchronously across the network. The fetch function will take in one argument, which is of course the path to the data/resource you want to fetch. Fetch returns a promise that resolves to the response of the request. We can then use the then() method in order to attach a callback once our promise has been fulfilled.
With fetch function and then method we can call the json() method on the response of our request which will provide us the response in json format. (JSON uses human-readable text to store data in the form of a key/value pair). The json method will return a promise, so you guessed it we will need to create a promise chain! We will pass the value we receive from the first Promise into our chain in order to do some operations. Below is an example of a basic fetch request:
.then(response => response.json())
.then(data => console.log(data));
Enjoy your fetching and remember to always keep your promises!