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)=>{
setTimeout(()=>{
 let check = store.includes("Reebok");
  
  if(check)
    resolve('My fav shoe brand is there!')
  else
    reject("Let's go somewhere else :(")
},3000)
})
Now invoke the promise

checkBrand
.then(data=>console.log(data))
.catch(err=>console.log(err))
//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) => {
 console.log(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) => {
 console.log(value);
})
.catch(err=>console.log(err))
//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.

References

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 info@amlgolabs.com
 or filling a contact form at the end of the page.

Comments

More Popular Posts

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.

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.

Polybase Blog - Introduction

Overview: This Polybase blog series is all about the use of Polybase Technology in today’s era to be able to take advantage of the Data(Relational and Non-Relational) by using T-SQL only. Data whether Big or not is the lifeline to many different sectors to cope up with Production, Maintenance, Predictions, Taking Precautionary Measures, Customer Satisfaction, Customer Retention, Sales, Revenue Generation and many more.

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.

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.

Stages of New Regulatory Reporting Implementation

In the last blog, we discussed what is  Financial Regulatory Reporting  and its importance in the banking industry. Regulatory Reporting comprises the submission of business numbers as required by regulators to evaluate and track the financial and operational status of financial institutions and their compliance with required regulatory provisions.