JavaScript Promises Unveiled: A Dual Perspective

Introduction to asynchronous JavaScript, Promise, and more…

The Coding Cube
4 min readJun 27, 2021
Photo by NONRESIDENT on Unsplash

In the late summer of 2016, my friend and I were assigned to a web development project for our summer term. Our mission: to create a dynamic weather web app, fetching data from remote APIs. However, he was grappled with the enigma of JS Promise as it was only first encounter with this concept. Luckily, drawing from my own JavaScript project experiences, I promised to resolve his confusions. Huddled in a corner of the cafeteria, he ventured to me his first, tentative question…

Question: Can you explain how promises work in JavaScript?

Promise in JavaScript is similar to the real-world promise in which we promise to do something or we may also acknowledge the possibility of failure. In JavaScript, however, the ‘Promise’ is used to manage the asynchronous operations. For that, you need to know about the background of Javascript’s execution of tasks.

Background:

Javascript has two main properties. It is single-threaded, which means it executes tasks one by one in a synchronous fashion. However, It behaves asynchronously (non-synchronous fashion) in a browser or a Runtime like NodeJs !!!

This raises the question: why does Javascript behaves asynchronously though it is a single-threaded? and more importantly, how?

Although it may seem contradictory at first, all operations in Javascript are performed synchronously on a stack which is called Call Stack.

In browsers or runtime environments (NodeJs), JavaScript does not have only its bare engine (like v8 or SpiderMonkey), but other additional components like APIs Collection, Callback Queue, and Event Loop are also bundled with it. Any callback method like setTimeout() is part of API Collection. These APIs may take some time to handle these events, but the main thread never stops. This is how javascript be single-threaded as well as asynchronous at the same time.

Runtime Environment Architecture

Question: Why does it matter?

Though in all ways Javascript is synchronous, its asynchronous behavior in a runtime often doesn’t meet our requirements. For example, if you want to execute a function /codeblock before executing another, knowing that the first one may take longer time than usual then async behavior doesn’t fit well.

The most accurate real-case scenario could be you are trying to fetch some data from a remote server, before rendering the list to the screen, or you want to send a post request to a remote server and after that, you are expecting a status. these need to be executed in the synchronous fashion.

So Promise is used to compel the runtime to act synchronously.

Question: How does JavaScript Promise solve this issue?

They say a Promise is an object that ensures the eventual completion (or failure) of an asynchronous operation. The Promise compelled the runtime to behave rightly and can process asynchronous operations synchronously. A Promise can have one of these three states:

  • Pending: Asynchronous operation is currently executing.
  • Fulfilled: The operation is completed successfully (resolve() is called).
  • Rejected: The operation is failed (reject() is called).

A pending promise can only be resolved or rejected. If either of these options happens and the associated method gets executed, we cannot invoke or revoke the Promise again.

The block structure of Promise

The whole Promise object splits into two blocks of codes. The first one is Producing block and the last one is the Consuming block. The Producing block usually takes time to complete, and upon completion or failure consuming block (.then) is invoked.

Remember the Producing code block is always executed synchronously, but Consuming code(.then) is always executed asynchronously.

Syntax of Promise

Now, Let’s refactor the withoutPromise.js to withPromise.js (synchronous fashion)

Observe how the Promise object (promise) has laminated the producing code (setTimeout) thenresolve function resolved the expected result A().

Though JavaScript Promises are fantastic features that you must have in your arsenal yet, they’re not without their own set of tradeoffs. Promise poses some substantial threats and issues that you must take care of while using it in a project such as:

Usually, a Promise is either resolved or rejected. But in some cases, a Promise can be rejected implicitly when an exception is thrown by a promise reaction. Such uncaught exceptions are not propagated through the regular exception handling mechanism of JavaScript.

Lots of third-party libraries provide different types of Promises to use, in some sense it might be painful to read every aspect of documentation to use those Promises aptly.

I hope you find this article handy.

The whole project is here: https://github.com/officialPrasanta/JavaScript-Blog-Codes

--

--