Promises in Node.js
- Anushka Shrivastava
- Oct 13, 2022
- 4 min read
Updated: Oct 13, 2022
While writing codes in JavaScript language, frequent use of nested callbacks can create chaos. But the functionality of nested callback functions are needed at a lot of places. To solve this, Promises are used in JavaScript.
PREREQUISITE
To understand promises, we need to have a basic understanding of JavaScript. You can refer to the following posts for the same -
QUICK LINKS -
Before getting into Promises, we also need to know about Synchronous and Asynchronous events in JavaScript.
SYNCHRONOUS AND ASYNCHRONOUS CODE IN JAVASCRIPT
Synchronous Code - It is the code which runs in sequence, which means each operation has to wait for the previous operation to complete before getting executed.
Example -
console.log('One');
console.log('Two');
console.log('Three');
// LOGS: One, Two, Three
Asynchronous Code - It is the code which runs in parallel, which means an operation can occur while another one is still being processed.
Example -
console.log('One');
setTimeout(() => console.log('Two'), 100);
console.log('Three');
// LOGS: One, Three, Two
WHAT IS A PROMISE?
A promise is generally an advanced or improved version of callbacks which handles all the asynchronous events. Instead of returning the final value immediately, an asynchronous method returns a promise to supply the value at some point in the future.
A promise can be in any one of the three stages. The three possible stages are -
Pending - which means the promise is in its initial state, neither fulfilled nor rejected.
Fulfilled - which means that the operation has been completed successfully.
Rejected - which means the operation has failed and has been rejected.
A promise is said to be settled if it is either resolved or rejected and not pending.
WORKING OF A PROMISE

When a promise is called, it is said to be in pending state. While a promise is pending, the calling function continues to run until the promise gets completed.
When a promise is completed, it either ends in resolved state or rejected state. The resolved state indicates that the promise was successful and the rejected state indicates that the promise was denied.
If promise ends in resolved state, the received data is passed to the then() method. And, if the promise ends in rejected state, the received data, called error is passed to the catch() method.
Next step is to consume the promise. We use .then() and .catch() methods to consume whatever data is delivered.
CODE FOR PROMISE
Let us try to understand the promises with the help of coding.
function getSum(a, b) {
const customPromise = new Promise((resolve, reject) => {
const sum = a + b;
if(sum <= 5){
resolve(console.log("Resolved"))
} else {
reject(new Error(console.log("Rejected")))
}
})
return customPromise
}
// consuming the promise
getSum(1, 8).then(data => {
console.log(data)
})
.catch(err => {
console.log("Oops!.. Number must be less than 5")
})
In the above code, we have created a function getSum() to compute the sum of two numbers a and b.
Within the function, promise constructor: new Promise() is used to generate a new promise.
Then, we have calculated the sum of a and b. If the sum is less than 5 or equal to 5, the resolve callback is executed. Otherwise, the reject callback gets executed.
The received data is also a promise. It needs to be consumed which is done via .then() and .catch() methods.
In the above code, then() method is executed when promise is fulfilled by the resolve() callback and catch() method is executed if the promise gets denied by reject() method.
So, the following code will display a message "Oops!.. Number must be
less than 5" as the sum would be greater than 5.
.catch(err => {
console.log("Oops!.. Number must be less than 5")
})
The OUTPUT produced will be -

THE promisify() METHOD OF NODE.JS
Promisification refers to the transformation of a callback-accepting function into a promise-returning function. The process of promisification helps in dealing with callback-based APIs for maintaining code consistency.
Node.js has an inbuilt module - util.promisify(). It enables to create promisification functions in JavaScript.
Let us try to understand this with the help of a code -
First, we need to create two files - promisify.js and promisify.txt
Our promisify.txt file will contain some text. Like -
"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer"
And, our promisify.js file will contain the following code -
// Importing the fs module
const fs = require('fs');
// Importing the util module
const util = require('util');
// Use promisify to fs.readFile to convert it to a promise based method
const readFile = util.promisify(fs.readFile);
// Reading the .txt file
readFile('./promise.txt', 'utf8')
.then((text) => {console.log(text);})
.catch((err) => {console.log('Error', err);});
In the above code, we have used the fs module to read the .txt file.
Then, util.promisify() method is used, to transform the fs.readFile into a promise-based function.
On running the following command in command prompt -
node promisify.js
we get the following as output -

With this, we come to the end of this post.
The post has covered up the basics of promises in JavaScript and Npde.js which was an important concept to cover. Hope you learned something new and enjoyed reading and coding.
Thankyou.
Recent Posts
See AllNode.js is an asynchronous platform. It does not wait for processes such as file i/o to finish. Instead, it uses callbacks. A synchronous...
Comments