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

Sherlynn Tan
Aug 18 · 2 min read

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.

The Startup

Medium's largest active publication, followed by +524K people. Follow to join our community.

Sherlynn Tan

Written by

Software Developer at Thoughtworks | Marathon Runner | Ex-Pharmacist Writing on Coding, Technology and Running

The Startup

Medium's largest active publication, followed by +524K people. Follow to join our community.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade