Simplifying Promises in JavaScript

August Radjoe
3 min readApr 1, 2020

--

These promises are easier to work with, trust me.

I have been working with JavaScript for two years, but when Promises come along, all I look up is “How to resolve promiseValue”. A few days back while working on my NPM package corona.js, I hit a roadblock. I fetched an API result, but it returned a Promise, not a JSON datatype. So, as a Computer Science undergrad, I used my three years of specialised knowledge to do what Engineers do best.

Just for the record, this query gave me this, you are not alone in frustration with promises, but I promise (heh) that it is super useful, you’ll see in a minute.

So what is a Promise?

Imagine you have to go to a fine dine, and you figure every table will be booked. So you call them up and ask to have your table booked. So when the table becomes avaiable you get it, and you don’t show up crowding the space. This is a vague analogy, but you get the idea. The Promise works in similar fashion. There are async functions to deal with, so a promise is an easy way to do. A promise can be in either fulfilled, rejected or pending state. You’d be returned with either a resolved value or a reason for failure. The moment you call the promise constructor, it will get to work right away. If you want more control, refer to Tasks (I came to know of this whie I was writing this article, very cool stuff, will write an article about it too!).

Let’s look at some C O D E.

var promiseFunction = new Promise(function(resolve, reject){  const flag = "True";
if( flag == "True" )
{resolve();}

else
{reject();}
});

So now you have declared a Promise constructor. How do we consume it? Welcome our next guest: THEN.

I love how JavaScript community just went: Fuck it, we will just call them what we think it is, “Here’s Promise, because it promises a value when you run it, and here’s then”. You will know why is it called “then”, it’s literally what it means 😂.

So to call a promise, you have to use the dot operator on your Promise and pass two functions, one dealing with the fulfilled state of Promise and one with Rejected.

promiseFunction.then(function() {console.log('Promise Accepted');}).catch(function () {console.log('Promise Rejected');});

Let’s run that shit up. Open your console, copy the first block of code, then copy the one above. You should get:

Why do we bother with Promises? Promises help you make your code reliable, and easier to debug. If you’re fetching APIs, they are almost always returned as promises. Learn to use them, you’ll be good.

I’ll get going, I don’t have a lot of patience.

Ciao,

Mir.

--

--

August Radjoe
August Radjoe

Written by August Radjoe

Now: MS CS @ Boston U / Prev: Ignite Tournaments, DeFi Alliance, Persistence, Eth India Co

No responses yet