Promises
To understand promises, it is necessary to first understand the distinction between
asynchronous and synchronous code execution.
Sync vs Async Code:
We will now create a function that simulates a database call by running a large loop and
printing "how are you?" at the end.
function fakeDatabase()
{
var sum = 0
for(var i = 0;i<1000000000;i++)
{
sum = sum + 1
}
console.log("How are you ?");
}
In the following code example, we will invoke the fakeDatabase function and then log a
message to the console
fakeDatabase() // first execution
console.log("Hi"); // second execution
The following execution log demonstrates synchronous code execution. The code
began running at 10:00:39, first computing the fakeDatabase function to print "how are
you?", and then moving on to the next statement "Hi" at 10:00:40.
PS C:\Users\kirangali\Desktop\node_js_learning> node .\promises_exp.js
12/29/2022, 10:00:39 AM
How are you ?
12/29/2022, 10:00:40 AM
Hi
In this case, the code is considered synchronous because it executes tasks one after
the other in a blocking manner. This means that the processor will wait for the database
call to finish before moving on to the next statement.
Asynchrnous Code:
Asynchronous code or Async code is in contrast to synchronous, executes the console
log “Hi” while the cpu computes/works on the fakeDatabaseCall.
asyncfakeDatabase().then(onSuccess, onFailure)
console.log("Hi")
PS C:\Users\kirangali\Desktop\node_js_learning> node .\promises
Hi
How are you?
PS C:\Users\kirangali\Desktop\node_js_learning>
It is important to note that the onsuccess and onfailure methods should not be a source
of confusion at this point. So don’t worry about them. Your understanding should simply
be that the processor executes the second statement "Hi" while the database call is
being processed and the data is being returned.
You may have questions such as:
● Why did the processor move on to the next statement instead of waiting for the
database call to finish?
● How does the CPU know to move on to the next statement?
● When does the processor actually find out that the database call has finished and
it needs to process the returned data?
So the idea is , asyncfakeDatabase returns a promise first instead of
returning the actual data from database.
Let’s write the function step by step to understand it better
Step1 : declare the promise inside a function, by default Promise takes
resolve and reject as parameters.
function asyncfakeDatabase(){
var promise = new Promise((resolve, reject)=>{
});
return promise
}
Step2: write the core logic inside promise construct
function asyncfakeDatabase()
{
var promise = new Promise((resolve, reject)=>{
var sum = 0
for(var i = 0;i<545454548;i++)
{
sum = sum + 1
}
});
return promise
}
Step3:
Now, it is time to explore the use of resolve and reject. Resolve is used to successfully
complete a promise, while reject is used to terminate a promise with an error. In this
case, since the database call is fake, we will use resolve to successfully complete the
promise if the sum of the loop is even, or reject to terminate the promise with an error if
the sum is odd.
function asyncfakeDatabase()
{
var promise = new Promise((resolve, reject)=>{
var sum = 0
for(var i = 0;i<545454548;i++)
{
sum = sum + 1
}
if (sum%2==0)
{
resolve("How are you?")
}
else{
reject("Failed to get data from DB")
}
});
return promise
}
Finally, we will now get into the part where we call this aysnc DB function and handle the
promise.
asyncfakeDatabase().then(onSuccess,onFailure)
console.log("Hi")
The above two lines can also be written as
databasePromise = asyncfakeDatabase()
databasePromise.then(onSuccess, onFailure)
console.log("Hi")
DB call returned a promise and promise has then method on it by default which takes
two functions as parameters.
We declared those functions
function onSuccess(resolve)
{
console.log(resolve);
//you can do something else as well here
}
function onFailure(reject)
{
console.log(reject)
//you can do something else as well here
}
If the promise was resolved, the onSuccess function will be called, and if the promise
was rejected, the onFailure function will be called.
Further reading:
In the above example, we rejected the promise if the sum was an odd number. In reality,
we may reject the promise if the database does not return the query result within a
certain time frame, which is known as setting a timeout on the promise.
Link for the above code: