Javascript Promises - How to Make and Keep Them.

Published Apr 17, 2017Last updated Apr 18, 2017
Javascript Promises - How to Make and Keep Them.

This post is a basic introduction to javascript promises and below is a list of what this post covers.

  • What are javascript promises?
  • How to make a simple promise? (Code included)

What are Promises?

One of the first things I was taught in my introduction to computer programming lectures was that the compiler/interpreter execute your program one line after the other starting from top to bottom which make sense since as humans, we can write our instructions like a list telling the computer the first thing to do on line one and what to do next on line two.

So I can write my programs like this:

1. nameOfUser = getUsersName();
2. print(nameOfUser)

It did not take a long time for me to see that this model of execution is not perfect as I think it to be.
Why?

You remember the saying that all fingers are not equal?
It turns out that the same principle applies to lines of code, all lines of code are not equal in that some lines of code take longer to execute.

You can think of the compilers and interpreters as town criers, they read your instructions to components of your machine in ways they can understand. How long it takes to get these things done is left to your machine and their communication network.

Sometimes, the instruction is executed and an error occured so the value you expect is not delivered. Sometimes, it takes the computer a while to get these things done and sometimes, bad things happen along the way but then, the compilier already told the machine and now, it has moved on to the next line of instruction.

Some computer programming language have in-built mechanisms of checking to see that the last line of code is properly executed before moving on to the next (asynchronous).

Unfortunately, Javascript does not have this capacity and that lead to the question, how do you ensure a line of code does not execute prematurely? How do you get one line of code to finish running before executing the next?

Think of one instance, the next line of code may depend on resource from an external server to function and considering the fact that you so not have control over how long it takes for the data to be available. In javascript, you can do this using a callback or making promises.

A promise is the eventual result of an asynchronous computation (such as call to fetch data from the server or reading a file) which may be available now, later in the future or never.

How can I make a Simple Promise
Promises are used on asychronous operations such as call to the request for data from the serve.

For sake of simplicity, we will use javascript setTimeout to simulate call to a server to request for a JSON file.

Here is our getUserData function which returns a JSON response.

const getUserData = () => {
   setTimeout(() => {
     return {
        name: 'Olawale Akinseye',
    country: 'Nigeria',
    url: 'https://www.codementor.io/brainyfarm'
     };
   }, 3000);
};
console.log(getUserData()); // undefined

Click Here to run this code on repl.it and you will see the output you get is undefined and that is because the function is asynchronous in nature and by the time the console.log runs, the code wrapped inside of the setTimeout is yet to run so we do not have our returned data yet (It needs 3 seconds).

How do we ensure the data is ready before logging it to the console? We can do this by wrapping the getUserData function in a Promise.

const getUserData = new Promise ((resolve, reject) => {
   setTimeout(() => {
     const userData =  {
        name: 'Olawale Akinseye',
    	country: 'Nigeria',
        url: 'https://www.codementor.io/brainyfarm'
     };
     resolve(userData);
   }, 3000);
});

getUserData.then((response) => {
  console.log(response);
});
// { name: 'Olawale Akinseye', country: 'Nigeria', url: 'https://www.codementor.io/brainyfarm' }

To run the code above, click here to run the code above and you will see we are able to successfully log the response data to the console just by wrapping the getUserData in the promise we created.

In the nearest future, I promise to talk more about these promises as we will explore the code and try to understand every part of it.

In the meantime, you can read more about promises on MDN Promise.

If you enjoyed reading this article, kindly share with other and follow me on Codementor or Twitter to be notified of new posts.

Discover and read more posts from Olawale
get started
Enjoy this post?

Leave a like and comment for Olawale

5