How to Use JavaScript Promises or TypeScript Promises

A simple explanation of how to deal with JavaScript promises and TypeScript promises.

Binge On Code
JavaScript in Plain English

--

JavaScript promises are important when the data we need is not immediately available. We will use a simple John and Jane birthday pact for this article.

How to use JavaScript promises or Typescript promises

Well, let’s be honest, at this time and age, time is often of the essence, we must all agree on this. But this does not mean that we cannot find ways to optionally be bound to it. We can have the choice of waiting or picking up where we left off, and these two concepts are what we will base our topic on today, JavaScript promises.

So, the best way to learn, in my opinion, is by making analogous comparisons to the real world. So, we will use a simple example, so that we have an understanding of what JavaScript promises are and actually how to use them.

Since TypeScript is a superset of JavaScript, then the same rules can be applied. So, the same logic can be applied when working with TypeScript promises.

Example Case

Well, John and Jane have been friends for years, and on either of their birthdays, they agreed that they would reward the birthday owner with a visit to the bowling alley. So, this is a pinky promise that they made and have to live by for the rest of their lives.

Well, this year was Jane’s birthday and for some reason, John’s paycheck was delayed, and was not able to deliver as expected on time, so he gave Jane two options:

  1. She could wait till the end of the month when John got paid and they go bowling.
  2. As soon as John had the money, he would take her bowling.

Well, I don’t know which option you would have gone with, but in my opinion, you would have gone with the one which suits you best.

Explanation using JavaScript promises

So, in the above simple analogy, there are a few keywords that we will use in order to bring a clear picture of JavaScript promises. These are:

  1. Birthday owner — but we will use Jane, as she is the owner in this case.
  2. Pinky promise.
  3. On-time.
  4. Wait till the end of the month.
  5. As soon as.

So, let’s begin breaking each part apart and see what is under the hood!

Code Setup

This is the complete code for this analogy. We will use it to explain how to use JavaScript promises, so you can refer to this as needed.

/**
* A pact between John and Jane, old time friends.
*
* NOTE: Some of the concepts such as resolving JavaScript Promises
* are not explained here.
*/
class JohnAndJanePact {
/**
* The agreed bowling voucher ticket value, irrespective of
* any delays.
*/
bowlingTicketVoucherValue = 1000;
constructor() {
this.makeClaim();
}
/**
* The birthday owner is the one who is charged with the role of
* making the claim for their gift.
*/
makeClaim() {

// Using patientjane
this.patientJane();
// To use eagerJane, simply uncomment the below line
// this.eagerJane();
}
/**
* She is the patient version of Jane the birthday owner.
*
* You will notice that patientJane's social life will be blocked until
* john fulfills his bowling gift voucher to her.
*/
async patientJane() {
const voucher = await this.endMonthJohn();
console.log(`End Month Salary Was Paid So John Sent Voucher -> ${voucher}`)
this.socialLifeOfJane();
}
/**
* She is the eager version of Jane the birthday owner.
*
* You will notice that eagerJane's social life will keep on rolling!
*/
eagerJane() {
this.sideIncomeJohn().then(voucher => {
console.log(`Side Income Came So John Sent Voucher -> ${voucher}`)
});
this.socialLifeOfJane();
}
/**
* The rest of her social life.
*/
socialLifeOfJane() {
console.log(`Jane's social life...`)
}
/**
* This john will wait for the end of the month to be paid.
*/
async endMonthJohn() {
return this.waitForSalary();
}
/**
* Simulate john waiting for his salary to be available.
*
* We are using 3000 as the default timeout to mock a salary
* at the end of the month, you are free to change this value.
*/
async waitForSalary() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(this.bowlingTicketVoucherValue)
}, 3000);
})
}
/**
* This john has a side income, so they will provide the
* voucher as soon as one of their side incomes generate a profite
*/
async sideIncomeJohn() {
return this.waitForEarlySideIncome();
}
/**
* Simulate john waiting for his early side income salary to be available.
*
* We are using a default timeout of 1000 to mock an early side income, feel
* free to change this value as well.
*/
async waitForEarlySideIncome() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(this.bowlingTicketVoucherValue)
}, 1000);
})
}
}
// instantiate the pact
new JohnAndJanePact();

Birthday owner

So, we can think of Jane as a portion of our program/code that expects data from another portion (John). Now, Jane, being a function, can continue going on with her social life as usual, OR, if it is absolutely necessary, she has to wait for John to meet his end of the bargain.

Pinky promise

Since John and Jane are bound by a pinky promise, and as we all know, you never break a pinky promise, then John has to ensure that either way, he needs to deliver. Thus, John will be bound to the promise and Jane will wait for the promise to be settled.

Now, if you think in terms of a JavaScript promise, it works in a similar manner. There has to be a party offering the promise and another consuming it.

By marking variants of john as being async, that implicitly makes them return a Promise by default.

Another thing to note is that we are marking patientJane as being async so that she can be able to wait for the promise to be resolved.

On-time

So, since John was not able to meet his end of the bargain on time then in this case, he has to give Jane the options we mentioned above.

Analogously, the same applies when working with JavaScript. A portion of a program can return the needed data immediately and always as expected without delay, OR it can go and fetch the data then provided it.

This is where JavaScript promises to come into the picture, and this is where we get our real-world definition of a JavaScript promise:

A commitment of a portion of your program to provide data to their caller at some future point in time.

So, that is basically my realistic definition of JavaScript promises. So, to further understand this, let’s focus on the term future point in time by understanding the last two keywords we listed above (4 and 5).

Wait till the end of the month

So, Jane has the option to wait till the end of the month for John to be paid. That means that all her social life will be put on hold until John’s bowling debt is paid.

Thus, this introduces a concept of JavaScript promises known as async-await. Well, as you can see, we have the await which is somewhat similar to wait. So, this will mean that Jane, will wait until John gets the money, which will be at the end of the month.

Similarly, when you use the async — await option, that means that the data that is needed will only be available after some time. Once the data is available, then it can be consumed.

Here we will use patientJane who will wait for endMonthJohn. Also, as pointed above, when working with JavaScript promises or TypeScript promises, for a function to be able to await another function, then that function has to be an async function itself. Thus, the reason we are marking patientJane as being async.

As soon as

Well, let’s assume another version of Jane who can keep on going with her social life as usual, even if John did not deliver on time! Thus, this means that as soon as John gets the money then they can go bowling.

The same applies to JavaScript promises. A portion of your program can listen for when data is available then it can consume it.

Here we will use eagerJane who will listen for sideIncomeJohn to tell her that he has the money, then they can go bowling!

Notice that since eagerJane is not waiting for sideIncomeJohn even though sideIncomeJohn is waiting for his side income, we are not marking her (eagerJaneB) as being async.

Finally

Well, clearly, you can now use JavaScript promises and apply the same when dealing with TypeScript promises. As you can see, Jane has two options, and so do you, when working with JavaScript promises or TypeScript promises:

  1. Wait for the results.
  2. Listen for the results when they are available and consume them.

Conclusion

This was a simple explanation of how to deal with JavaScript promises and TypeScript promises alike.

With that said, till the next one!

Happy Coding!

Are you interested in learning JavaScript? Checkout similar awesome articles here: Related Articles

More content at PlainEnglish.io. Sign up for our free weekly newsletter. Follow us on Twitter and LinkedIn. Join our community Discord.

--

--

You love programming? Well, we do! We are a team of one as of now and are really passionate about programming and making the world better today than yesterday!