What is Js Promise?

Kishan Kesari Gupta
TechVerito
Published in
9 min readMar 6, 2021

A promise is a JavaScript object, generates a value not certainly known when created. It performs an asynchronous action to return a value with fulfilled or rejected reason. It achieves a similar purpose as function callbacks but with many new features and also precise syntax.

Initialize syntax of a promise carries resolve and reject parameters. The successful execution of the promise shows resolve function call and failure shows reject function call.

History of Promise

In the olden days, web applications have consisted of static data on HTML pages. Therefore now web applications have become communal and dynamic. That makes an increase in intensive operations such as requests for external networks to fetch Web APIs data.

A Javascript is a single thread programming language that follows a synchronous execution process. It executes one operation at a time, but methods like request different Web APIs can take time depending on the data size is requested and bandwidth speed. If a request for several external networks to fetch web APIs data, performed synchronously, then the web application takes time to load for each user interaction to the application. Such applications are tough to handle. It will block the user for some time until the fetching web APIs data operation completes.

To stop blocking performance. A Javascript can access data from Web APIs asynchronously. It executes parallel operations instead of sequential. It helps the user to continue using the website as asynchronous tasks are processed.

A Javascript that does not use an asynchronous Web API will process code synchronously.

Executing the function and the output based on an order is called.

When Javascript uses asynchronous Web API with an event loop, then the process will be complex. We will set a timer and perform tasks after a specified time. A setTimeout runs asynchronously without freezing the web application.

The setTimeout function runs asynchronously and takes two arguments i.e. function and time. A function passed to setTimeout will run when the time counter is finished.

Executing the function and the output not based on an order is called.

Here console.log in the second function called asynchronously will execute after the synchronous function. In this scenario, the browser works with a concept named event loop to manage parallel events or concurrency control. A Javascript executes one task at a time. It wants to inform the event loop when to execute which statement.

The setTimeout asynchronous function executes after the execution of the synchronous function. But if we want to run any synchronous function after an asynchronous function. Then this problem is solved by function callbacks.

A function passes to another function as a parameter known as a function callback. Callbacks work on asynchronous purposes, whether it’s not asynchronous by nature.

Function callbacks examples:

Execute first and second and pass the third function as a parameter to the second.

It executes the first function and delays the execution of the third function until the asynchronous setTimeout task in the second function completes. It happens because the third function passed as a callback argument to the second function.

The callbacks are a useful way to delay the execution of a function. It requires when a function has dependencies. And the function is dependent on another function data for further processing. In such scenarios, nested callbacks are used to process data. These nested callbacks increase code complexity with many asynchronous requests, and these nested callbacks are called callback hell.

An asynchronous code in the real world is more complex, and there will be much error handling and passing the response to other functions. It becomes unmanageable to handle through callbacks.

To prevent an unmanageable callback, the concept of the promise was invented in ECMAScript 2015.

How event loop is used, the context of the promise

  • If we were working on the synchronous execution stack, the setTimeout function would cause the execution to stop for a few seconds (thus blocking the program), so there would be no way to do anything else while we wait for the counter to finish. To solve an Event loop is imposed that allows the task to perform synchronously.
  • Since the time of execution of the callback function is unknown. And when the stack is empty, then the event loop adds things from the queue callback. It may be a necessary nesting call within the callback of our function, is something called a hell callback.
  • A promise came into the picture in ES6. It has these states, pending, fulfilled, rejected. We can attach a callback through the then instruction to execute code once the value resolves by promise.
  • Promises and their callbacks are different from asynchronous callbacks. The promised callbacks added to the new queue is a microtask queue, which is a program for things happening immediately after the script that is currently running. These microtasks are immediately processed by macro tasks.

How promise works

Here, a promise explains through the producer and consumer problem. A producer accesses APIs to return data of a website or new feature that belongs to the website and notify consumers or clients when a website with a new feature is live.

Let us understand promises with real-life programming examples:

A production team will call the website’s new feature Web API. It takes time to return data over a network. As data successfully returned, then It gives a notification to clients about the product’s new feature.

A promise is a JS object that executes the product’s new feature Web API. This API call needs time to produce the promised result(fulfilled value or rejected reason), and the “promise” makes that result open to all of the clients.

The syntax for constructing a new promise object:

The function declared inside a promise is the product Web API. When a new promise object is formed, then the function product Web API starts automatically fetching data for the website and when it finishes with success returns the result.

The arguments resolve and reject are callbacks. When the product Web API gets results quickly or takes some time. Then It can call one of these callbacks as shown in the next examples.

  • resolve: Return a result value after successful execution of the promise.
  • reject: Return an error object after the promise execution process failed.

The promise object has the following state:

These are the state when the new promise is constructed and returned:

  • Initial State (pending): When a new promise object is created and has a default “pending” state till promise execution starts.
  • Final State (fulfilled or rejected): When the execution of a promise finishes successfully with a result in value, a state change to “fulfilled”. And if the promise execution process fails with an error, a state change to “rejected”.

The syntax for resolve and reject:

  • Resolve scenario:

A new promise is formed with resolve and reject arguments. Inside promise, there is an if statement having condition calling product new feature Web API function to return new features data for the website. If the product’s new feature Web API successfully returns data of new features, then the condition will be true and executes a resolve callback statement.

  • Reject scenario:

A new promise is formed with resolve and reject arguments. Inside promise, there is an if statement having condition calling product new feature Web API function to return new features data for the website. Hence the product’s new feature Web API is not able to fetch new features data due to network error, then the condition will be false and executes the else block having a reject callback statement.

Now it’s time to notify the clients or consumers that their feature is ready or not?. It will be possible with then & catch block.

The syntax for then, catch, finally:

  • Then block:

The then block of promise contains two arguments. First result arguments run when a promise is resolved. And the second error argument runs when a promise is rejected.

We can also provide only one argument to then block executes when a promise is resolved. And this above promise then block will notify clients or consumers with an alert message that some new features are added to the website.

  • Catch block:

The catch block of promise executes when a promise is rejected with an error message. And this promise above will notify clients or consumers with an alert message that It takes time to introduce new features.

  • Finally block:

The finally block always runs when a promise is resolved or rejected. This block is required for deallocating resources which are not in use.

How promise chaining works

  • Sequence execution of then block:

A promise provides multiple tasks to be executed. The whole chain will work because a call to a .then block returns a promise. So we can call next .then block and so on. The execution of the above architecture is given in the below code:

A promise chain will resolve when each .then block executes successfully. The .then block will run in sequence one after the other. When the product Web API will fetch data for the website successfully, the first .then block will run for fetching new features data for the website, the next .then block will give notification to clients or consumers. This is how promise chain architecture executes.

  • Independent execution of the block:

A promise has an independent .then block. Both blocks do not pass results to each other. They work independently or have parallel execution. The execution of the above architecture is here:

Here, we have two independent .then blocks. One is associated with notifying clients or consumers through emails, and another notifying clients or consumers through SMS. They work independently, and they do not pass results to each other. These .then blocks will start their execution only when the product’s new feature Web API will fetch new feature data successfully, then the promise will resolve.

Conclusion

This article gives information to manage the asynchronous operation is a necessary part of JavaScript. An asynchronous operation can handle in different ways. But a promise is an effective solution that came in ECMAScript 2015, overcomes the drawbacks of callbacks.

Want to get in touch?

Please reach out to me on LinkedIn.

--

--

Kishan Kesari Gupta
TechVerito

Lead Software Engineer | Full Stack Web Developer | Technical Consultant | Research Analyst