Use Promises over Callbacks, and How to Create a New Promise in Javascript

Sherlynn
The Startup
Published in
2 min readAug 18, 2019

--

Promises are widely used instead of callbacks. Promises are a great feature in Javascript that enable you to avoid callback hell, especially when you need to wait on a response from multiple API requests that are asynchronous.

A Promise is a special Javascript object that represents the eventual result of an asynchronous action. A promise is kind of a proxy for a value that we don’t have yet.

A promise object has 2 internal properties:
1. PromiseStatus
2. PromiseValue

A promise can be in 1 of 3 states:
1. Pending
2. Fulfilled — action fulfilled successfully
3. Rejected — action has failed

There is a class in Javascript called Promise. If you want to create a new promise, you would simply need to create a new instance of this class.

const myPromise = new Promise((resolve, reject) => {});console.log(myPromise);

Initially, the promise is in pending state:

Chrome console. Promise in pending state, with undefined value.

The resolve and reject parameters are functions. We would need to invoke the resolve function in order to transfer the promise to the fulfilled state or invoke the reject function to set the promise to the rejected state.

The resolve function takes in an argument which is the value of the promise. Resolving the promise:

const myPromise = new Promise((resolve, reject) => {
resolve('value')
});
console.log(myPromise);
Resolved promise.

The reject function take in an argument which is the reason why the promise is rejected.
Rejecting the promise:

const myPromise = new Promise((resolve, reject) => {
reject('rejected reason')
});
console.log(myPromise);
Rejected promise.

That’s it.
From the above, we learned about how we can create a promise, and how the status and value of the promise can be changed.

--

--