JavaScript Promises 101
Tags: asynchronous, javascript, promises, es6
Published: 2019-06-25 13:52:37

---
title: JavaScript Promises 101
published: true
description: Promise.resolve('I understand Promises');
tags: #asynchronous #javascript #promises #es6
---


# What is a Promise in JavaScript?
Definition:

<i> A promise is an object that may produce a single value some time in the future: either a resolved value, or a reason that it’s not resolved.</i>

##Real life example

“Imagine you are a kid. Your dad promises you that he will buy you a new toy next week”

That is a **promise**. A promise has 3 states:
1. Pending: You don’t know if you will get the toy
2. Fulfilled: Dad is happy and he will get you a toy
3. Rejected: Your dad is not happy, he withholds the toy

## What is Asynchronous programming?

In programming, we can simplify the definition of synchronous code as “a bunch of statements in sequence”; so each statement in your code is executed one after the other. This means each statement has to wait for the previous one to finish executing. Asynchronous code takes statements outside of the main program flow, allowing the code after the asynchronous call to be executed immediately without waiting.

## State of Promise:

![Promise-states](https://thepracticaldev.s3.amazonaws.com/i/jhzesqxefydl9yd1ntaf.png)

*Promise Syntax:*
  ![Promise-syntax](https://thepracticaldev.s3.amazonaws.com/i/738msx21ev1mcexu0dod.png)


##Consuming Promises:

Let's create our first Promise and see how to consume it:

![Promise-consume](https://thepracticaldev.s3.amazonaws.com/i/g1xcxbefcfunol46vvmw.png)

## Promises are asynchronous!

When JavaScript is executed, synchronous code has the potential to block further execution until it has finished what it’s doing. Long-running JavaScript functions can make the UI or server unresponsive until the function has returned. Obviously this can result in a terrible user-experience.

Let's relate back to our real life example:

![Promise-async](https://thepracticaldev.s3.amazonaws.com/i/ag0npa9yf5gpn5bnaxab.png)

Probably you expected this as the output?

![expected-output]
(https://thepracticaldev.s3.amazonaws.com/i/s3piehbeet4wp45h38ej.png)

However, the actual output sequence is:

![actual-output]
(https://thepracticaldev.s3.amazonaws.com/i/m24p7tnggo86hnelh0vu.png)

You, the kid, wouldn’t stop playing with your old toys while waiting for the new toy. Will you? That’s something we call **asynchronous**, the code will run without blocking or waiting for the result. Anything that need to wait for promise to proceed, you put that in `.then`


## Why do we use Promise?
Prior to promise we had callbacks. A callback is a function that is to be executed **after** another function has finished executing — hence the name **call back**.

![callback](https://thepracticaldev.s3.amazonaws.com/i/rdqpv0lnz4eywz5l2n0x.png)

The above code snippet refers to a **Callback hell** since we nested the code four times. In order to escape from callback hell we use **Promise**. 

![why-promise](https://thepracticaldev.s3.amazonaws.com/i/h19utg625ipeasvuzakb.png)

This is a perfect example of chaining promises. It's a proper way to tell JavaScript the next thing to do after an asynchronous task is done. The result of the then method is a Promise. 


## Promises.Race()
Promise.race is a JavaScript built in function that accepts an iterable of Promises (e.g.Array) as an argument. This function then **asynchronously** returns a Promise as soon as one of the Promise passed in the iterable is either resolved or rejected.

![Promise-race](https://thepracticaldev.s3.amazonaws.com/i/72cqry6i1cha9d9340qi.png)


## Promises.all()
Promise.all is a promise that takes an array of promises as an input and gets resolved when all the promises get resolved or any one of them gets rejected.

For instance, we have five promises, all make async requests such as fetching data from database, Promise.all will return a resolve or reject state based on the promises execution. *Promise.all is itself a promise.*

![Promise-all](https://thepracticaldev.s3.amazonaws.com/i/e4jwo9jcjrufvabqxcfv.png)


## Error Handling:

Error objects that are thrown inside promises, hence they won’t tell you anything about the sequence of actions which led to the error; all they’ll tell you is the file and line number where the error was created. So we need to use better error handling mechanism to log these errors.

![Promise-error-handling](https://thepracticaldev.s3.amazonaws.com/i/uk691d3g3hx09ytt1god.png)

If there are no errors **.catch** doesn’t trigger at all. But if any of the promises rejects (a network problem or invalid json or whatever), then it would catch it.

## Promise.reject()

Promise.reject() returns a Promise that is rejected. It is highly used for debugging purposes and error catching.

![Promise-reject](https://thepracticaldev.s3.amazonaws.com/i/xoik9hoom6j48l0wq5gz.png)


## You made it!

Promises have become an integral part of JavaScript. Don’t worry about the new kid on the block **Observables** just yet. Hopefully this article helps you to master the basic building blocks for Promise.