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.
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.
Code flow explained
The promise can be created in below fashion:
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.
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.
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!
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
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.
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
(MAS, APRA, HKMA, EBA, FED, RBI etc) all major regulators in the world
and our team is specialized in commonly used regulatory tools across the
globe (AxiomSL
Controller View, OneSumX Development, Moody’s
Risk, IBM 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
Post a Comment