DEV Community

Cover image for JavaScript Promises Explained By Gambling At A Casino
Kevin Kononenko
Kevin Kononenko

Posted on • Edited on

JavaScript Promises Explained By Gambling At A Casino

If you have ever gambled or watched a movie about gambling, then you can understand promises in JavaScript.

We all love the asynchronous capabilities of JavaScript. In fact, we love them so much that sometimes, we overindulge. And then we get code that looks like this “pyramid of doom”.

Image Credit

This is commonly known as “callback hell” because you probably don’t want to re-read that code and try to understand how everything works, and in what sequence it works. In fact, nobody on your team does either.

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 encourage straightforward, single-purpose functions that will allow you to write clear code and understand every step without headaches. After thinking about it for a while, I realized that promises are just like a trip to the casino. While a casino “modifies” the amount of money in your bank account (ahem, removes), a chain of promises modifies data in a specific sequence.

So, let’s jump into it. 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.

What is a promise?

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. Or perhaps you will get lucky, and end up winning money?

You get to your hotel room, then head down to the casino. Each type of game accepts cash, so you will need to go to the ATM to withdraw $1000 and get started.

Let’s take a step back and think about this scenario. Although cash can be used for anything outside of the casino, it means one thing inside- the number of games you have left before you run out of money. That cash amount will likely shrink further and further over the course of the weekend. It could also grow, but you have already promised yourself that you will not lose more than $1000 this weekend.

Notice how your remaining money amount gets passed from game to game in the diagram above?

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.

Promises pass the products of one asynchronous function directly into the next function. That function will start as soon as the previous function has returned a value. Or, if it returns an error, you will run a different function. We can cover that contingency later.

Creating Your First Promise

There are actually two types of promises: producer and consumer.

The producer is the first promise in the chain, while the consumers wait on a result from a previous promise in the chain. In this case, going to the ATM is the producer, since you need money to play games (obviously).

Also, a promise can have one of three states:

  1. Pending- has not completed yet
  2. Fulfilled- Promise has completed and returned a value
  3. Rejected- Promise has completed with an error or failed.

So, if you visit an ATM, and you fail to complete the operation that you intended… well, you may not have the $1000 in your bank account and should exit the casino immediately. If you successfully withdraw $1000, then you have returned a value.

So let’s turn this into code. Here is the promise syntax.



let withdraw = new Promise(function(resolve,reject){

  let amount = visitATM(1000);
  return resolve(amount)
});


Enter fullscreen mode Exit fullscreen mode

And here is a line by line explanation of that code.

promisecodeblock2.jpg

Line 1- Declare the promise with two possible results: fulfill or reject

Line 2- A function to withdraw money from the ATM

Line 3- Return a settled state with the value from the visitATM function

Just like any other asynchronous code, this approach allows your code to wait on the status of the visitATM function. There’s no point in continuing if that isn’t completed!

Chaining Multiple Promises

Let’s assume that you want to play slots, poker and roulette while you are at the casino. Each one requires you to buy-in via cash. Of course, if you bet too much money on poker and run out, then you will not be able to play any of the following games.

Let’s say that you want to play slots first.



let withdraw = new Promise(function(resolve,reject){ 

  let amount = visitATM(1000); 

  return resolve(amount) 
}); 

withdraw.then(function(amount){
  let slotResults = playSlots(amount, 100);

  if(slotResults <= 0)
    throw err;

  return slotResults;
});


Enter fullscreen mode Exit fullscreen mode

Promises use the .then syntax to show what should happen after the previous promise is settled , or completed. In this case, the final result of the withdraw promise is contained within amount.

So, when we set up the next promise using .then(), we also name the argument amount to correspond to that previous result.

One other important note- playSlots is a made-up function. We are imagining that it takes two arguments – the total amount of money you have, and the amount you are willing to gamble.

Let’s add another step to this promise chain- a game of poker. It will work similarly to the slot machine promise. We will gamble as much as we want in this one.



withdraw.then(function(amount){
  let slotResults = playSlots(amount, 100);

  if(slotResults <= 0)
    throw err;

  return slotResults;
})
.then(function(slotResults){
  let pokerResults = playPoker(slotResults);

  if(pokerResults <= 0) 
    throw err; 

  return pokerResults;
})


Enter fullscreen mode Exit fullscreen mode

So, we feed whatever cash remains after playing slot machines into the poker game. Pretty aggressive, if you ask me.

Here’s a code diagram of this part.

Let’s imagine that we have now gambled away all our money. Although we originally intended to play more games, we have no money left. There may be more promises added in this chain, but we will not be able to settle them.

Instead, since we have $0 left after poker, this promise will throw an error. It is still settled , but in a rejected state.

This is where the .catch() method comes in handy. Catch allows us to handle any errors that may occur in our promise chain. We don’t need to write error handlers for each callback.

Let’s imagine that you head straight to the bar when you have gambled all your money. Here’s what that looks like in code.



withdraw.then(function(amount){
  let slotResults = playSlots(amount, 100);

  if(slotResults <= 0)
    throw err;

  return slotResults;
})
.then(function(slotResults){
  let pokerResults = playPoker(slotResults);

  if(pokerResults <= 0) 
    throw err; 

  return pokerResults;
})
.catch(function(e){
  goToBar();
});


Enter fullscreen mode Exit fullscreen mode

This one catch statement will work regardless of which promise is rejected.

Using Objects Within Promises

So far, our promises have only returned a number. But, they can also pass any other type of data along the chain.

Let’s imagine that you played a slot machine, and won some money. The slot machine does not give out straight cash- it gives you a ticket that you can redeem later. That’s called the ticket-in, ticket-out system.

Now, you need to track two values throughout the chain- the amount of cash on hand, and the value of your tickets. An object would work best in this situation.

Let’s modify the second promise in the chain, where you played slots.



withdraw.then(function(amount){
  let ticketValue = playSlots(amount, 100);

  if(ticketValue <= 0)
    throw err;

  return {tickets: ticketValue, cash: amount};
});


Enter fullscreen mode Exit fullscreen mode

You are now returning an object with two properties. Here is what that looks like:

The poker table will only accept cash for chips, so you need to use that property in the next promise.



withdraw.then(function(amount){
  let ticketValue = playSlots(amount, 100);

  if(ticketValue <= 0)
    throw err;

  return {tickets: ticketValue, cash: amount};
})
.then(function(slotResults){
  let pokerResults = playPoker(slotResults.cash);

  if(pokerResults <= 0) 
    throw err; 

  return {tickets: slotResults.tickets, cash: pokerResults};
})
.catch(function(e){
  goToBar();
});


Enter fullscreen mode Exit fullscreen mode

Notice a couple things:

  1. I only used the cash value in the poker game. But, at the end, I still need to add the ticket value into the final object in order to pass it along the chain. Otherwise, I would have lost my winnings.
  2. slotResults contains the object from the previous promise, even though that object did not have a name.

Get The Latest Tutorials

Did you enjoy this explanation? Check out the CodeAnalogies blog to get the latest visualized tutorials of HTML, CSS and JavaScript.

Top comments (43)

Collapse
 
tunaxor profile image
Angel Daniel Munoz Gonzalez • Edited

Thank you for not using new Promise(); Multiple times, just once and then (badum tss) just chaining .then() that's how promises should be used.

I've seen so many tutorials around using/abusing new Promise(); when .then() already returns promises.

Edit:
I think I was not clear, bright explanation I really liked the reading and your example! keep writing more stuff!

Collapse
 
kbk0125 profile image
Kevin Kononenko

Haha I appreciate it Angel! Definitely clear.

Collapse
 
tiodetac profile image
Tiodetac

I don’t think that there are the best online casinos that can be named like that. Gambling is pretty subjective so it mostly depends on what you like to play online. For example, if you ask 100 people who play online casino games, 55 of them will tell you that the nettcasinorsk.com/mrgreen/ with the most slots is the best one, while 30 will say a casino with the best live casino games is the best. The remaining 15 will likely say that as long as there’s a bonus they’re more than happy to dedicate time.

Collapse
 
andrews29 profile image
Andrew Smith • Edited

Maybe your casino is good and pretty interesting but in my opinion it doesn't fit this forum. First of all your casino has some significant disadvantages, it looks like a blog, which makes it unattractive, it is on another language, so how could people understand how to play, and the games are totally different for our market. If you want to make a good product, you can have mega88a.com/id-ID/Home as the best example for our market. It is my favourite platform, because it fits my preferences and it offers me a lot of bonuses.

Collapse
 
okegaming profile image
okegaming • Edited

Maybe your casino is good and pretty interesting but in my opinion it doesn't fit this forum. First of all your casino has some significant disadvantages, it looks like a blog
okegaming

Collapse
 
ggreen profile image
Ginger Green

Zebet Casino se destaca por sus atractivas promociones y bonos para nuevos jugadores, así como para los clientes habituales. Los jugadores pueden disfrutar de ofertas como giros gratis y bonos en sus depósitos, lo que mejora aún más la experiencia de juego.

Collapse
 
txtorres profile image
DTorres

My favorite is Incan Adventure Slot jackmobilecasinos.com/mobile-slot/... Incan Adventure is a good and exciting break from the regular video and fruit slot machines. It comes with a plan, which makes it all the way more challenging. I got to this site several months ago, when was messing around. Guys gathered a dope selection of various casino slots overviews. You can check the list of popular casinos where is better to play in real-money mode, check information about game features, some bonuses and useful hints for cool gaming!

Collapse
 
bettybel profile image
Bett

looks not bad, but it's a more like a blog I think

Collapse
 
aritdeveloper profile image
Arit Developer

This was an awesomely REFRESHING walkthrough! Now you've got me excited about Promises! Thank you so much for taking the time and effort to produce this intelligent, visually-appealing post! I shall take a page from your book as I start writing my own tutorials :D

Collapse
 
kbk0125 profile image
Kevin Kononenko

Thanks Arit :)

Collapse
 
grason777 profile image
grason777

I use the best application for online casinos jackmobilecasinos.com/mobile-free-.... I tried many different companies, but I chose this one. I noticed that I often go with the phone, because they have a good mobile application and it is very convenient to receive the money won. They even have free spins. And as soon as I started using the services of this application, I started to win more. That's a coincidence?)

Collapse
 
jennycasino profile image
Jenny Casino

Despite the fact that new online casinos are launched several times a month, ultimately only a small fraction of the huge number of playgrounds deserve the attention of gamers. For a long time, gambling operators can work hard to create one or another gambling club, which aims to enter the TOP 10 online casino, and most importantly, become a favorite of the audience. But not everyone succeeds in this, because today there is great competition in the online gambling market and each operator is trying with all his might to show its viability. But as we all know, demand creates offers, especially for high-quality online casinos jennycasino.com/top-rated-online-c... , and this forces operators to develop the latest projects of ultra-modern gambling houses and offer customers favorable terms of cooperation.

Collapse
 
yatiac profile image
Rafael E.

at some point you stopped using slotResults and started using ticketValue but kept validating slotResults.

Collapse
 
kbk0125 profile image
Kevin Kononenko

Hey Rafael, can you point to a specific code block? I will check it out.

Collapse
 
yatiac profile image
Rafael E.

Sure!

All the code blocks after the paragraph named "Using Objects Within Promises"

withdraw.then(function(amount){
  let ticketValue = playSlots(amount, 100);

  if(slotResults <= 0) <---- HERE 
    throw err;

  return {tickets: ticketValue, cash: amount};
});

perhaps it should be something like

if((ticketValue + amount) <= 0)
    throw err;

or validate them separately in case you could use just tickets even if amount is <= 0.

Thread Thread
 
kbk0125 profile image
Kevin Kononenko

Good point! Just fixed two cases.

Thread Thread
 
okegaming profile image
okegaming

Maybe your casino is good and pretty interesting but in my opinion it doesn't fit this forum. First of all your casino has some significant disadvantages, it looks like a blog
okegaming

Collapse
 
tomwhite1122 profile image
TomWhite1122

Good one! I'm running online casino sites.google.com/ so it was quite helpful for me.
How many years are you coding? Because I would never write a code like this by myself. Anyway thanks for the code and good explanation!

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
denzyr748r7 profile image
Denzy

the VPN server based on their preferences in addition to restrictions. What can be more? all data you transmit, including document messages, notes as well as Web proxy extensions, are sent via encrypted systems. With all your security information at one glance, you can increase your privacy, and provide additional security options for browsing. In short, the NordVPN Torrent file has been all about safety using the top-standard encryption algorithms. Download Avast Premier License Key File for a lifetime.

Collapse
 
denzyr748r7 profile image
Denzy

It is also compatible with Multi-Stream. This means that you can watch films, songs, or television series without having to download them multiple times. So, FlixGrabis a top time-saving application that is at hand to assist users. You don’t need to be concerned about video quality or audio quality in this program The reason for this is because it will inspire you to make movies that are in HD quality. Here is where you can download the most current version PicsArt Studio. Photo Studio. This application can be used in HD 720P or 1080P formats.

Some comments may only be visible to logged-in visitors. Sign in to view all comments.