JS Promises Explained
A Quick Example
Before I get started I will show a quick example of an implementation of promises for reference.
1 | function createPromise(input){ |
Introduction
A lot of the power of JavaScript comes from the fact that it’s an asynchronous language. This means that we don’t have to wait for one operation to finish before moving on to another. Some languages do this with threading, but sine JS is a single-threaded language, we use callbacks or promises.
If you are already familiar with the concept of a callback then a the idea of a promise should be pretty easy to grasp. A promise works in much the same way as a callback but allows us to write cleaner code that is is easier to read and debug.
A phrase often used in programming is “Callback Hell”. Simply put this is the state of having too many callbacks nested inside of each other. One calling the other and each pushing your next block of code further to the right.
Callback Hell?
1 | function thing(num,data,callback){ |
Expected Output:
1 | Data: Thing 1, |
Of course this is an overly simplified example that doesn’t really do anything that requires callbacks, but hopefully the point has been illustrated.
So How Do Promises Help?
Here is the same logic but using promises instead of callbacks.
1 | function thing(num,data){ |
As you can see this code isn’t much shorter but it is much easier to read and involves less scrolling to the left.
How Do I Actually Use These Things?
Here is a bare-bones example of how to implement a promise. First we create a new promise, then we resolve it.
1 | function createPromise(input){ |
The expected output would be:
1 | 2 |
Here is the same logic using callbacks for reference:
1 | function createCallback(input,callback){ |
The expected output would also be:
1 | 2 |
What About The Real World?
In real life, none of the examples so far have actually done something asynchronous. Like I said above, this is the real power of promises. So let’s go ahead and setup an actual real life example of using promises.
For this example we are going to read some data from an external JSON file and then iterate through it listing the names in the file.
1 | //NodeJS |
[NOTE] Async/Await
We can also make use of the new await
functionality. This allows us to use promises in a little more friendly manner.
1 | var test = function (data){ |