Mark As Completed Discussion

Promises

You now know what callback hell is and what it looks like. But how do you solve it? For that, we have promises in JavaScript. They were introduced in ES6 and can be a confusing topic for many. Let’s try and understand the syntax for Promises, how its internals work, and how we can use them to solve callback hell.

Promises

A promise object has two attributes, a status, and a value. As you can see above, when we create a new Promise, the status is pending and the value is undefined.

The status can take one of three values; fulfilled, rejected, and pending. As their names suggest:

  1. fulfilled is when the promise has been resolved
  2. rejected is when it gets rejected, and..
  3. pending is when it has been neither resolved nor rejected.

In an actual scenario, we pass in two callbacks to the Promise constructor, known as resolve (or res) and reject (or rej). These two methods are used when the promise needs to be resolved or rejected. The argument passed to the resolve method is the value associated with it and the argument for the rejected method is the value associated with it.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment