A few things are difficult about the above example:
- Unclear error handling. What happens if something goes wrong?
- Each function depends on the previous function. You do not need the asynchronous style. You want to make the order clear to others reading the code. When you chain this many functions together, a synchronous style of code will be more readable.
- You need to continually track the variables for input into a function, and then output. And also track the logic that happens to each output. This becomes exhausting.
You could make this entire process more understandable using promises. If you are like me, you may have heard of promises once or twice, but then ignored them because they seemed confusing. The basic uses of promises are actually pretty easy if you understand callbacks.
Promises are kind of like going to the casino, and if you are looking to clean up a nasty code block, they are an excellent solution. Promises encourage straightforward, single-purpose functions that will allow you to write clear code and understand every step without headaches.
Note: If you do not have experience with callbacks, check out my explanation on the principles of callbacks. If you are looking for a more technical explanation of promises, check out this guide or this guide or this video.
Let the betting begin!
A promise holds the place of a value that does not yet exist, but will certainly exist in the future. This allows you to clearly follow a function and understand its beginning and end. As shown above, promises are a great way of giving clarity to consecutive asynchronous functions and clarifying inputs and outputs.
Let’s say that you are taking a weekend vacation to a casino. You have two weeks of salary in your pocket, and you are going to enjoy every moment as you bet it away, down to the last dime. You get your hotel room, then head down to the casino. The tables at the casino do not accept cash, however. You need to head over to a cashier station to exchange your money (let’s say $1,000) for casino tokens, like these guys:
Stop right here. This is the beginning of a promise! You have a known value to start, but it is a stand-in, not a final product. You can’t spend these casino tokens outside of the casino floor, and you didn’t come to the casino to collect casino tokens. You went there to play games, and casino tokens are the starting point that will allow you to translate your $1,000 cash into a final product, hopefully more than $1,000.
After you get your tokens, you try all your favorite games. You play 20 hands of blackjack, bet 30% of your money and lose $200. That was quick. You move on to roulette, and bet 5% on black until you win $50. You move on to poker, bet 50% of your money, then lose $500 after you get too confident.
Here is that process in code: