JavaScript Promises - Building a Simple Promise Example

sachindra149 profile image sachindra@work ・2 min read

Promises are one of the most important topics in Javascript. This post is simply to help us understand the basics of Javascript Promises.

As per https://mozilla.org, a Promise is an object representing the eventual completion or failure of an asynchronous operation. Essentially, a promise is a returned object to which you attach callbacks, instead of passing callbacks into a function.

Promises are processes that are already happening while you execute the code block. These are very useful when we work with asynchronous operations. Prior to the advent of Promises, we had been using events and callbacks but these had limited functionalities and while the callbacks grew larger, the operations became unmanageable. This is termed as ‘Callback Hell’. Here the return value of one function is dependent on another function and so forth.

Promises can help us operation on multiple asynchronous tasks easily and provide better error handling than what we had with callbacks and events.

A Promise has four states:
1. pending: Initial state, Promise is still pending i.e not fulfilled or rejected yet
2. fulfilled: Action related to the promise succeeded or the operation has been completed successfully
3. rejected: Action related to the promise failed or failed operation

A Promise is usually created via a constructor.

let promiseObject = new Promise(executor);

Here “executor” is a function that is passed with the arguments “resolve” and “reject”. The “executor“ function is executed immediately by the Promise implementation thereby passing “resolve” and “reject” functions. In fact the “executor” function gets called before the Promise constructor returns the created object. Then the “executor” performs the asynchronous operations and once done, it calls either the “resolve” function or “reject” function depending upon what the returned object is. The return value of the “executor” function is ignored.

Promises can be consumed or used by registering methods like .then and .catch.

_1. _.then __ is invoked when a promise is resolved
_2. _.catch __ is invoked when a promise is either rejected or some error has occurred in execution.

Creating a Promise:

function getNewTemperature() {
return new Promise((resolve, reject) => {
let result = 'Testing';
const delay = Math.floor(Math.random() * 10000);
const temp = Math.floor(Math.random() * 300 + 1);
setTimeout(function() {
if(temp > 200) {
result = Too Hot | Delay: ${delay} | Temperature: ${temp};
} else if(temp < 100) {
result = Too Cold | Delay: ${delay} | Temperature: ${temp};
} else {
result = Just Right | Delay: ${delay} | Temperature: ${temp};
reject('Error displaying data');
}, delay);

Consuming a Promise:

getNewTemperature().then((res) => console.log("res: ", res)).catch((err) => console.log("err: ", err));


Editor guide