Promises are cool and exciting little bits of logic that I was certainly confused about when I first heard about them but now, after a bit of toiling, and deep dives into unnecessary information to “do them right”, I kinda get them. Now I would like a place where people like myself can go to find out and understand promises without as much effort that I went through.
Here is a basic structure of a Promise using the example from above, I will show a few equivalent ways in which to perform the task I require as well as build on the knowledge demonstrated to show some potential for the Promise. If you would like to know about the then, resolve, request and catch functions skip past the code examples and that is where I go into a little detail about each.
In this example, I show that you can just set a promise to a variable and use it after the fact rather
In the following example, the twitter library is used to make a tweet with the information acquired from the bitly api call.
As you can see in the examples above there are a few core elements which remain persistent throughout the structure of a promise:
Resolve is a little tricky, it allows you to pass the data (the response (res)) to the ‘then’ cascaded method by resolving/finishing/executing the current method being called, in this case is the request call. This is the component which allows you to ‘wait’ for the call data and pass it on when the call is completed.
Then is chained to a promise, in fact you can chain them as many times as you want! It is the function that is waiting for resolve to pass it along the data where you can do what you want with the data and pass it along to the next then.
The reject function is used when there is an error, if executed it throws the error all the way to the end of the then chain where the function ‘catch’ hooks it.
Catch is where you handle the error that is thrown, I have not seen anything other than a basic console.err(err) at this stage but I am sure someone will let me know otherwise. The amazing thing about this method in terms of error handling is that you only need to have one place to catch all of the errors whereas with callback functions you need them on every callback!
If you have come this far and read the article, thank you very much for reading my first blog post! If not still thanks for visiting! If you have any suggestions, question or want clarification please feel free to let me know! I will be making another blog post on the Promise.all function pretty soon and how it blew my mind even more than just vanilla promises so watch this space!