DEV Community

loading...

JavaScript Promises 101

niharikapujari profile image Niharika Pujari Updated on ・3 min read

What is a Promise in JavaScript?

Definition:

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.

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

Promise Syntax:
Promise-syntax

Consuming Promises:

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

Promise-consume

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

Probably you expected this as the output?

expected-output

However, the actual output sequence is:

actual-output

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

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

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

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

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

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

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.

Discussion (0)

Forem Open with the Forem app