JavaScript: Learn Promises

JavaScript Promises made easy. Learn the basics in 5 minutes.

Brandon Morelli
codeburst

--

Udemy Black Friday Sale — Thousands of Web Development & Software Development courses are on sale for only $10 for a limited time! Full details and course recommendations can be found here.

What will I learn?

This tutorial will teach you the basics of Promises in JavaScript. This is not an all-inclusive article, but instead will provide you with the basic knowledge you need to understand and begin using Promises in your code.

Why do we need Promises?

Promises (like callbacks) allow us to wait on certain code to finish execution prior to running the next bit of code.

Why is this important? Think about a website that loads data from an API then processes and formats the data to display to the user. If we try to process and format our data before the API has even fetched the information, we’re either going to get an error or a blank website. By using a Promise, we can ensure that the API data isn’t processed/formatted until after our API call has succeeded.

What is a Promise?

In JavaScript, a Promise represents the eventual result of an asynchronous operation. Think of it as a placeholder. This placeholder is essentially an object on which we can attach callbacks.

Our Promise can have one of three states:

  • Pending — Asynchronous operation has not completed yet
  • Fulfilled — Operation has completed and the Promise has a value
  • Rejected — Operation has completed with an error or failed.

A promise is settled if it is not pending. Once a Promise has settled, it is settled for good. It cannot transition to any other state.

Working With Promises

Most of the time when working with Promises, you will be consuming already-created promises that have been returned from functions. However, you can also create a promise with it’s constructor.

Here’s what a simple Promise might look like:

runFunction().then(successFunc, failureFunc);

In the above example, we first invoke the runFunction() function. Since runFunction() returns a promise, only when the Promise is settled can our successFunc, or failureFunc function run. If the Promise is Fulfilled, our sucessFunc is invoked. If the Promise fails, our failureFunc is invoked.

A Promise Example

Now lets look at an example where we create our own Promise. It’s okay if this doesn’t make sense yet:

function delay(t){
return new Promise(function(resolve){
return setTimeout(resolve, t)
});
}
function logHi(){
console.log('hi');
}
delay(2000).then(logHi);

Above we have two functions — a delay() function and a logHi() function. The logHi() function simply logs 'hi' to the console. The delay() function is a little more complicated. It returns a Promise that will resolve after a supplied time frame.

We use the then() method to register callbacks to receive either the eventual fulfilled or rejected value.

With this in mind, we can use delay(2000).then(logHi) to pass in 2000 milliseconds (2 seconds) into our delay function. After 2 seconds have passed, our Promise will resolve, and only then will our logHi function be invoked.

You can try this out yourself by opening up the Google Chrome Developer Tools and typing the above code into your console!

Chaining Promises

One of the main benefits of Promises is that they allow us to chain asynchronous operations together. This means we can specify subsequent operations to start only when the previous operation has succeeded. This is called a Promise Chain. Here’s an example:

new Promise(function(resolve, reject) {
setTimeout(() => resolve(1), 2000);

}).then((result) => {
alert(result);
return result + 2;
}).then((result) => {
alert(result);
return result + 2;
}).then((result) => {
alert(result);
return result + 2;
});

Above, our initial promise is going to resolve in 2000 milliseconds with a value of 1. After resolving, the then() handler is called and the value of 1 is alerted to the screen. Finally, the value is added to 2, and our new value of 3 is returned. This value is passed on to the next then() handler, and the process repeats.

Obviously this is not a real world example, but it should illustrate for you how Promises can be chained together. This is very useful with certain tasks in JavaScript such as loading external resources, or for waiting for API data before processing it.

Error Handling

Up until this point, we’ve only dealt with resolved promises. That’s about to change. We can use .catch() to catch all of our errors in our Promise chain. Lets look at what a .catch() might look like:

// ....
})
.catch((e) => {
console.log('error: ', e)
}

Above I’ve created a simple .catch() that will take the returned error message and log it to the console. Lets add in error handling to the previous example now.

Below, there are only two changes. After the second .then() I’ve added in an error and an error message. I’ve also added our .catch() to the end of the chain. What do you expect to happen when this code is run:

new Promise(function(resolve, reject) {
setTimeout(() => resolve(1), 2000);

}).then((result) => {
alert(result);
return result + 2;
}).then((result) => {
throw new Error('FAILED HERE');
alert(result);
return result + 2;
}).then((result) => {
alert(result);
return result + 2;
}).catch((e) => {
console.log('error: ', e)
});

Here’s what happens:

  • Our Promise resolves after 2 seconds with a value of 1
  • This value is passed to the first .then() and alerted to the screen. 2 is added and a new value of 3 is passed to the second .then()
  • A new Error is thrown. Execution stops immediately and the Promise resolves to a rejected state.
  • .catch() receives our error value and logs it to the screen. Here’s what it looks like in the console:

Closing Notes:

Thanks for reading! Additional information can be found on Promises here, here, and here. Hopefully this has been a good introduction to Promises for you! If you’re ready to finally learn Web Development, check out the The Ultimate Guide to Learning Full Stack Web Development in 6 months.

I publish 4 articles on web development each week. Please consider entering your email here if you’d like to be added to my once-weekly email list, or follow me on Twitter.

If this post was helpful, please click the clap 👏button below a few times to show your support! ⬇⬇

--

--

Creator of @codeburstio — Frequently posting web development tutorials & articles. Follow me on Twitter too: @BrandonMorelli