Skip to main content

Promises in JavaScript

Hello Techies, in this blog we will discuss about Promises in JS. JavaScript (JS) is a lightweight, interpreted, or just-in-time compiled programming language with first-class functions. While it is most well-known as the scripting language for Web pages, many non-browser environments also use it, such as Node.js, Apache CouchDB and Adobe Acrobat. Let’s begin!

Brief Introduction

A promise is an object that signals completion or failure of an asynchronous task and its result. It means using promises we can ensure that our task will get completed or failed in some time in future, so that we don’t have to wait for its completion to execute next task.

Need for promises

Javascript executes everything line by line. But when we want to execute a slow process like fetching a file from a server we cannot do it traditionally since it will block our browser and severely affect the performance of our application.

Callbacks were introduced to solve this problem, wherein you pass a function inside another function and the former is called when the latter has finished its execution. But soon with a lot of callbacks passing inside one another, readability became a problem, popularly known as callback hell.

async1((err, res) => {
  if (!err) async2(res, (err, res) => {
  	if (!err) async3(res, (err, res) => {
  		console.log('async1, async2, async3 complete.');

ES6 introduced Promises to resolve this problem. They use callbacks under the hood. But Promises provide a clearer syntax that chains asynchronous commands so they run in series.

Creating and invoking a promise with an example

Let’s create a shoe store.

let store = [‘Adidas’, ‘Reebok’, ‘Puma’, ‘Sketchers’];
Let’s create a promise to check brand of the shoes.

const checkBrand = new Promise ((resolve,reject)=>{
 let check = store.includes("Reebok");
    resolve('My fav shoe brand is there!')
    reject("Let's go somewhere else :(")
Now invoke the promise

//My fav shoe brand is there!

Code flow explained

The promise can be created in below fashion:

const myFirstPromise = new Promise((resolveFunc, rejectFunc) => {
  // do something asynchronous which eventually calls either:
  //   resolveFunc(someValue)        // fulfilled
  // or
  //   rejectFunc("failure reason")  // rejected
A Promise object is created using the new keyword and its constructor. This constructor takes a function, called the "executor function", as its parameter. This function should take two functions as parameters. The first of these functions (resolve) is called when the asynchronous task completes successfully and returns the results of the task as a value. The second (reject) is called when the task fails, and returns the reason for failure, which is typically an error object. Both resolve and reject functions are provided by the constructor at the time of promise creation.

Some useful methods of Promises

Promise.all(): When you go to a shoe store you tell the sales person your requirements and if he promises all your requirements being fulfilled then you buy the shoe.

const checkColor = Promise.resolve(“Blue”);
const checkDiscount = '10%';
//checkBrand = ‘Reebok’
//Check the definition above
Promise.all([checkColor, checkDiscount, checkBrand]).then((values) => {
//[ 'Blue', '10%', 'My fav shoe brand is there' ]
It takes an array of promises and returns array of resolved values or if any one of them fails then it returns the rejected value irrespective of whether others were resolved or not.

Promise.any(): Suppose you and your friend go to two different stores looking for same shoe specification, i.e. Blue colored Reebok shoes with 10% discount and whoever finds it first buys the shoe.

const checkStore1 = new Promise((resolve) => setTimeout(resolve, 100, 'store1'));
const checkStore2 = new Promise((resolve) => setTimeout(resolve, 500, 'store2'));
const promises = [checkStore1, checkStore2];
Promise.any(promises).then((value) => console.log(value));
It takes an array of promises and as soon as any one promise is resolved it returns the resolved value or if all of the promises failed to resolve then it returns aggregated error.

Promise.race(): Take above example, you and your friend went for shopping but if you saw a store with people not wearing any mask you race away as fast as you can from the shop!

const checkStore1 = new Promise((resolve, reject) => {
  setTimeout(resolve, 500, 'store1');
const checkStore2 = Promise.reject('no masks!');
Promise.race([checkStore1, checkStore2]).then((value) => {
//no masks!
It takes input as an array of promises and as soon as any one promise fulfils or rejects, it returns with fulfilled or rejected value.

In this blog we have seen what are promises, why do we need them, what is callback hell, how to create and apply Promises in our code. Similar to these are async/await. They are syntactical sugar over Promises but it saves us from writing then() chains which becomes unreadable with too many Promises pieced together. In the coming blogs we will discuss some more interesting topics about JavaScript.


About Amlgo Labs : Amlgo Labs is an advanced data analytics and decision sciences company based out in Gurgaon and Bangalore, India. We help our clients in different areas of data solutions includes design/development of end to end solutions (Cloud, Big Data, UI/UX, Data Engineering, Advanced Analytics and Data Sciences) with a focus on improving businesses and providing insights to make intelligent data-driven decisions across verticals. We have another vertical of business that we call - Financial Regulatory Reporting for (MASAPRAHKMAEBAFEDRBI etc) all major regulators in the world and our team is specialized in commonly used regulatory tools across the globe (AxiomSL Controller ViewOneSumX DevelopmentMoody’s RiskIBM Open Pages etc).We build innovative concepts and then solutions to give an extra edge to the business outcomes and help to visualize and execute effective decision strategies. We are among top 10 Data Analytics Start-ups in India, 2019 and 2020.

Please feel free to comment or share your views and thoughts. You can always reach out to us by sending an email at
 or filling a contact form at the end of the page.


More Popular Posts

Amlgo Blog - Experience The Experiments

Amlgo Labs Blog  is a step towards our vision to share knowledge and experiences, Amlgoites accept every challenge very enthusiastically. We do experiments, we fail but we learn and build complex solutions to help our clients solve their problems in Data, Analytics, Prediction, Forecasting, Reporting, Designing and Development area. During this process we enjoy immense learning everyday and we have decided to share our thoughts, learnings, experiments and experiences so that we don't work in silos and contribute the best of our knowledge towards community and learn more by views and reviews. This website is maintained and brough to you by  Amlgo Labs Professionals .   Our Strong Basics -  1)   KISS (Keep It Simple and Straightforward) :  We believe most of the problems can be solved by keeping things simple and straight. This is the learning we had in past, sometimes we try to solve technical problems using high end algorithms and complex codes but this results into complications.

Power BI Blog - What is Power BI and Why we use Power BI.

This Power BI blog is an introduction to the Power BI. In this Power BI tutorial, you will learn Power BI basics - what is Power BI, Power BI Desktop and Power BI Service. Power BI tool is a combination of Business Intelligence and Visualization. Before we dig deep let’s understand what is Business Intelligence. Business Intelligence is a broad spectrum which consists of using different business strategies and techniques to gather data, refine it and process it for the purpose of data analysis which gives us some meaningful information which helps in data driven decision making. When we present this information in the form of some charts, graphs it takes the form of Visualization.

Power BI Card Visual With Conditional Formatting

In this blog we will take you through the Power BI Card Visual and a workaround to present card with conditional formatting. To know more about what is Power BI please do check Power BI Blog . The conditional formatting, we do will not be on the Card Visual, but the output will certainly look like Card, which is a requirement in some cases. Many Power BI users have used Card Visual to represent some value on the Power BI Reports separately or on above of any other visual, but sometimes clients ask which is deemed difficult to achieve, but not impossible. So, let’s dive into the practical to know more about it.

A simplified view of a QlikView tool:

In our last blog related to Qlikview, we discussed the use of Qlikview for Financial Data Analytics . Qlikview is a Business Intelligence tool that consists of a front end to visualize the processed data and a back end to provide the security and publication of the mechanism for QlikView user documents.

Polybase Installation for Scale-Out process

This part is the continuation of the previous blog about the introduction of  Polybase Scale-Out Group . As we have discussed in our earlier blog PolyBase enables your SQL Server instance to process Transact-SQL queries that read data from external data sources. SQL Server 2016 and higher can access external data in Hadoop and Azure Blob Storage. Starting in SQL Server 2019, PolyBase can be used to access external data in SQL Server, Oracle, Teradata, and MongoDB.

JavaScript: The Important Basics

In this weird world of technology people often get confused how does a website work? What all things should I be aware of? So we are here to help you. Most of the content on web is developed with the help of JavaScript. JavaScript is really becoming popular these days with the coming of ECMAScript2015 and ECMAScript 2016, for this reason, some beginners learning React and Angular and are also trying to tackle more modern JavaScript syntax at the same time. If you're new to both, it can be confusing as to "what is JavaScript and what are its important features". This document should serve as a primer to help you get up-to-speed on JavaScript syntax that we feel matters the most for learning React as well as Angular.

How to Connect Windows with Ansible?

Hello Techies, this blog is the continuation of the last blog Install Ansible on Windows which is the second part of the series Ansible with Windows . Before you proceed, I recommend you to please take a look at the introductory blog of this series so to have an understanding of this series.