JavaScript Promises Explained

Richard Chea
1 min readDec 14, 2020

The introduction of promises in ES6 was released to help work with callbacks. There is a term called, “callback hell”, that refers to a situation where you have nested callbacks to the point that it affects the readability of your code.

A JavaScript promise is an object that can be returned synchronously after the completion of a chain of asynchronous tasks. There are three states that the object can be in when returned.

  1. Pending: This is a state where the promise hasn’t returned a final value yet and can be transitioned into one of the other two states.
  2. Rejected: This state is where an error has been thrown and the task has failed.
  3. Fulfilled: This state is where the tasks have thrown zero errors and have completed successfully.

Out of these three states, both the rejected and fulfilled states are considered settled because it’s no in a pending state where you’re returned an error or completion of the task.

Now that you have a better understanding of a promise, we can look into what it can do to help with the readability of your code.

The example below shows what a nested callback looks like and can be hard to read and even harder to manage.

demoFunction(args, function() {
firstFunction(args, function() {
secondFunction(args, function() {
thirdFunction(args, function() {

With promises, you can use a .then() to chain them together instead of nested callbacks.

.then((args) => firstFunction(args))
.then((args) => secondFunction(args))
.then((args) => thirdFunction(args))

The .then promise chains help clean up the code and allow for easier readability.