Hello Folks….
Today I am going to share about what is Promise in java script. This is one of the topics that were not clear to most of the developers who uses java script.
This demo is to make you understand what promise are and how asynchronous functions are going to work
This post covers with a demo on how to use Promises in java script. so let’s get started.
What is Promise?
Promise is a object that holds the eventual result of an asynchronous Operation
What it means is Promise is an class which can hold the results of an asynchronous operation.
Asynchronous operations (or) function which require some time to get the results that we want to display or preform some actions. For example, If we want the data of a student from the database it requires some time to execute the commands of API calls to retrieve the data from the data base. Those actions are called as asynchronous operation.
In order to understand promise in simplest way promise is like our parents making us promise that they will by us chocolate. In the same way promise function will give us result like it promised us.
There are two results that a promise function will give us such as Resolve and Reject
This Promise can do this asynchronous operations without affecting the other operations that are executing with two main keywords Async & Wait
Async is an keyword which is used to declare a function as asynchronous which means this function will take some time to get executed. In other words this async function will talk to other services like database, API calls etc.
Wait is a important keyword that must use if a function is using a promise class. It will wait until the operation is getting executed.
If you don’t understand what is wait keyword don’t worry i will make you clear this in practical section.
Promise in code (practical)
Alright lets get our hand dirty.
1) Create a new java script file
Open your favorite code editor and make sure your code editor has correct extensions for running a java script file.
In this demo i am going to use Visual Studio Code(VSC)
2) Creating functions
In this demo we are not going to use any API or retrieving data database.
This demo is to make you understand what promise are and how asynchronous functions are going to work
In this demo we are going to create a simulation of getting users details, users git hub repositories and commits they have done.
create a function called getUsers which takes user id as parameter
function getUsers(id)
{
return new Promise((resolve,reject)=>
{
setTimeout(()=>
{
console.log('Reading a user from a database');
resolve({id:1,name:'Arun'});
},
2000);
});
}
If you guys don’t know what setTimeout function means it is an asynchronous function which allocates some time to get executed. It take two parameter a function that need to be executed and time in milliseconds for how long this function needs to be waited.
NOTE - this functions is used for simulation
getUsers function returns a new Promise Object.
Promise function takes one parameter as function. This function takes two parameter Resolve and Reject.
Resolve is a object which is used when the function is returning the data which we want to return .
Reject is a object which is used when the function may return error when we are not sure about it.
getUsers function will return JSON-like object which we want and we are sure about it so we are calling resolve and sending the value that we want to send to those consumers who are using this function.
3) Create two more function
This is to get better understanding.
I want you readers as practice create two functions for getting users github repositories and getting users commit as like before we did and then see my code down below.
function getUserRepositories(username){
return new Promise((resolve,reject)=>{
setTimeout(()=>{
console.log('Calling Github API...');
resolve(['repo1','repo2','repo3']);
},2000);
});
}
function getCommits(repo){
return new Promise((resolve,reject)=>{
setTimeout(()=>{
console.log('Calling Github API');
resolve(['commit']);
},2000);
});
}
4) Creating Async function
As we told earlier if you are going to use Promise we need to create a function as asynchronous with the help of async keyword
async function userActions()
{
const users = await getUsers(1);
console.log(users);
}
In this function i created a variable called users which will store the user details.
Here i used await keyword because it is a promise function. It promises us that it will return a result right? so we have to use await keyword.
If you run this code it will take exactly 2 seconds to get execute and will log the output in the terminal
Output:
What if we didn’t use await keyword??? Lets check it out!
create a new constant for getting users GitHub repositories
async function userActions()
{
const users = await getUsers(1);
const repositories = getUserRepositories(users.name);
console.log(users);
console.log(repositories);
}
Output:
Note Promise {} because we never use await function to give sometime for that promise function for getting the result.
> ‘If you want something give sometime and work it will come to you’.
So trust promise function and use await keyword. lol
Reject Parameter
So far we have seen about Resolve parameter. Now we are going to see about reject parameter .
Reject parameter is used when a error might occur. This can be used to perform some actions or we can throw error to the user.
Below code will throw error using reject parameter.
function rightToVote(age){
return new Promise((resolve,reject)=>{
if(age>=18)
{
resolve('You can vote');
}
else
{
reject('You are under age');
}
}
);
}
async function demo(){
const result = await rightToVote(18);
console.log(result);
}
Output:
So this is all about promise and async function.
SUMMARY
1.We have seen about what is promise function
2.what is asynchronous function
3.Then we saw about what is async and await keyword.
4.We created a demo code for practicing about promise function.
5.The we saw about what are resolve and reject parameter in promise
function.
Thank you for reading this blog guys.. we will meet in new blog with new topic
Chearssssssssss 🥂…..




Top comments (0)