Promises

Glossaries
But Before we deep dive into this Amazing and complex concept of Promises, You need to firstly know all of these terminologies or tech jargons:
You must have used government websites, and you knows how fast they are, and in times of results, result publishing sites website are not even able to load there logo, then you must have thought that why the lag that much, because even more traffic is handled by google every time, then why that much lag.
The lag is occurring because of Synchronous operation or blocking Code. Because These Websites consist lots of blocking code which tries to run all users request in a single thread like structure and if we use operations that takes time like reading or loading file, then it takes time. OR “Running code line by line in a sequential order is called Synchronous operation, where code waits for completing first request or code line before starting second request or code line.”
This problem can be solved by Asynchronous operation. Where we run all users request separately and they runs on background and they never wait for completion of any operation that takes time to run other line. OR “Running code is non-sequential order like multiple threads and solving request of each user as another thread in the background, and it never waits for completing first line to run the second line.”
Callbacks are just calling another function inside any function Or Nested Function where one function is called inside other.
Now, before we know what promises is and why it is required, we firstly need to know:
History of Promises
A Promise is a special construct, added to JavaScript in 2015 as part of a big language update. But can you Imagine What Engineers do to perform tasks like “loading data of user after data loaded from data base” and these types of things. Now from the Government Website example, we found that one of it’s solution is writing asynchronous code which doesn’t block the main thread.
And at that time, we uses nested callbacks for writing asynchronous code like this:
const fs = require('fs')
fs.readFile('./README.md','utf-8',function(error,content){
if(error){
console.log(`Error Found: ${error}`)
}
else{
console.log(`File read Successfuly ${content}`)
}
})
And these can look simples firstly, but let’s imagine a situation where you need to read a file and then copy its content to a another file and then just delete this present file. This may look simple but let’s show you, how it would look like in async(asynchronous) operation with Callbacks:
const fs = require('fs')
fs.readFile('./hello.txt',function(error,content){
if (error){
console.log("Error found during reading hello.txt file: ",error)
}
else{
console.log(`hello.txt read successfuly`);
fs.writeFile('backup.txt',content,function(error,content){
if (error){
console.log(`erro is creating backup.txt file: `,error)
}
else{
console.log(`backup.txt file created succesfully.`)
fs.unlink('./hello.txt',function(error,content){
if (error){
console.log(`Error occured in deleting hello.txt file: ${error}`)
}
else{
console.log(`hello.txt file deleted succesfully.`)
}
})
}
})
}
})
Now I am sure that this code is enough complex to make fear on your mind, and these types of async functions with callbacks inside callbacks inside callbacks are called call back hells.
And in most of legacy codes(older written code), you can find these callback hells because at that time, these types of modern and advance features like Promises were not available.
Now let’s Finally understand what Promises is:
Promise
Promises in programming is similar as in real life. It help to write asynchronous operations and it returns a promise that it will return the result, when the operation/task will be completed or even rejected.
It have three States:
Pending State: When the operation/task is in the progress and not completed yet.
Fulfilled State: When the operation is/task completed successfully.
Reject State: When the Operation/task is rejected and not able to be completed due to errors, bugs or permissions.
And It mainly have three callback(calls the input function) methods also:
.then() : will be executed when the task is successfully completed or fulfilled
.catch() : will be executed when the task is rejected or in-completed.
.finally() : will be executed in end of both completed and in-completed.
Uses of Promise
It is used to write asynchronous code. Let’s try to do the same task that we done with callbacks:
const fsPromises = require('fs/promises');
fsPromises
.readFile('./op.txt','utf-8',function(error,content){let contents = content})
.then((contents) => fsPromises.writeFile('backedUp.txt',contents))
.then(()=>fsPromises.unlink('./op.txt'))
.catch((error)=> `Error occured: ${error}`)
Now You can see how much easy and simple to use these Promises.
Now what if I would say that it is not the real Promise. Don’t be confused, I used the “fs” module also with the promise to get the methods like “writeFile”, because promises only consist these 3 methods: “.then”, “.catch”, “.finally”. And these methods are available is fs module.
Promisification
So to use these types of methods in the promise, we create our own promises in this way:
function readFilePromise(file,encoding){
return new Promise (function(resolve,reject){ // "reject" = will store the error and "resolve" = will store the content if error not found
fs.readFile(file,encoding,function(error,content){
if (error){
reject(error) // will return the errro to "reject" if error is found
}
else{
resolve(content) // will return the content on reading to resolve
}
})
})
}
Here we can see that, Internally we are using “fs” module but now this function will return an Promise, and the code we had written above using “fs/promise” had also used the same things to create all these methods available there.
And converting these Legacy codes(example of long Callback hells) to support these promises(what we did above) is called Promisification.
And similarly you can create promises of and method available at “fs” module. You just need some knowledge of Polyfills, because it is some similar to that. Now let’s check our above code that is it working properly:
readFilePromise('./op.txt','utf-8',function(error,content){let contents = content})
.then((contents) => writeFilePromise('backedUp.txt',contents))
.then(()=>unlinkPromise('./op.txt'))
.catch((error)=> console.log(`Error occured: ${error}`))
.finally(()=> console.log("All Done"))
And we can see that it is working properly.
But we had to know that it’s an asynchronous code and will not block the code to wait for it, but the code from 2nd to 5th line will work similarly to synchronous because third line will not able to work before completing the second line.
Async and await
Now you knows that Programming is continuously evolving and a word called Syntactic word(which means just improving the code readability). So programmers also made it’s syntactic sugar, using await and async like this:
async function doTasks() {
let reading = await readFilePromise('./op.txt','utf-8')
await writeFilePromise('backedUp.txt',reading)
await unlinkPromise('./op.txt')
}
“async” in js is a keyword used to define a function which will work asynchronously and a async function returns a promise and when the “await” keyword is used inside a async function, then it pauses the execution of that line(function) until the awaited or above promise is resolved or rejected. Or you can just say that “await” will not work until the awaited (or already in await state function) is not completed.
Now, we are programmers, and we like errors, so to handle error situations also, we can use try keyword also like this:
async function doTasks() {
try{
let reading = await readFilePromise('./op.txt','utf-8')
await writeFilePromise('backedUp.txt',reading)
await unlinkPromise('./op.txt')
}
catch(error){console.log(`Error occured: ${error}`)}
finally{
console.log("All Done")
}
}
And even here, we are using “catch” and “finally” keyword which are methods of promise.
Hope you found this blog Helpful and learned something. Make sure to hit on the like Icon only if you found reading this blog helpful, otherwise dislike it. And have a nice Day.
Subscribe to my newsletter
Read articles from Manish Saw directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
