Basics of using Promises

Benjamin Cunningham
letsboot
Published in
2 min readMar 12, 2018
Asynchronous Slinky

You want to run JavaScript asynchronously otherwise stuff would freeze in the browser. So you often have to tell something that it should execute your code when some event happened. You do that by handing over callback functions to all kind of events, that then will execute your callback in the future. Often you end up nesting stuff, like if someone presses a button, your function “get data from server” is called which then hands over a callback “show data” to the event when the server responded.

This often ends up looking like that, this is called the Callback Hell Chirstmas Tree:

call1(function(something) {
call2(function(something) {
call3(function(something) {
console.log(“callbacks from hell”)
});
});
});

So that’s why we need something to handle that, and that’s why we use promises. Promises are handlers wrapped around your code which will in turn execute code one after another unlike basic JS that will return whichever code is loaded first.

There are three types of states for Promises:

  1. Pending: the initial code is not fulfilled or rejected
  2. Fulfilled: where the code is executed successfully
  3. Rejected: Where the code fails and is rejected.

The best thing about promises is that only once the current argument is settled, and only then, will the next argument will occur.

How to create a promise

Now let’s look at a callback hell example:

Callback Hell Example

In the addNumbers function we use the jQuery callback API. In this example we aim to add 2 numbers together and adding another 2 numbers after the result of ‘a’ and ‘b’. Here is the intended outcome: ‘a’ results in 9, ‘b’ results in 19, and ‘c’ results in 42.

And here is the fix using promises, and this time Fetch API:

Callback Hell fixed

This time we use the Fetch API to merge our code whilst using promises. From the previous example, we also use Thening. By removing the callbacks, and using .then, the code is executed asynchronously.

Using promises is a great way to make your code run asynchronously and to keep your code clean and structured in an orderly fashion. Using Fetch and other APIs to write your promises, is another great way to simplify your code.

--

--

Benjamin Cunningham
letsboot

I live in Basel, CH and I aim to become a front end web developer. I have started working as a Co-Trainer and a Software Engineer at Letsboot.