DEV Community

Ashok Naik
Ashok Naik

Posted on • Updated on

Beginners guide to Promises in Javascript

A Promise in JavaScript is an object which holds the completion status of an asynchronous operation. The completion status can be Resolved, Rejected, Pending.

Alt Text

States of Promises

Resolved: A promise is resolved state when there are no errors returned during the execution of the promise.

Rejected: A promise is rejected state when errors occur during the execution of the promise.

Pending: A promise is pending state when the result is not
ready.

Promises are used to carry out asynchronous tasks like network requests. Using Promises we can write clean and understandable code. Promises were meant to avoid the nesting of callbacks.

Let's look at an example that will help us understand Promises in a better way.



const promise = new Promise((resolve, reject) => {
 let allWell = true;
  if(allWell) {
    resolve('Promise Resolved!');
  } else {
    reject('Promise Rejected');
  }
});
promise.then((result)=>{
    console.log(result) 
}).catch((result) => {
    console.log(result)
});
//Output:  "Promise Resolved!"


Enter fullscreen mode Exit fullscreen mode

In the above example, the promise variable holds the response of the completion status rejected, resolved, pending. As the value is allWell is true the promise is resolved and the message Promise Resolved! is returned.

Promises are really great when something is going to take a long time in the background like fetching information from a database table we can resolve and carry on with execution and handle if something goes wrong by returning an error message.

Let's look at another example



const promise1 = new Promise((resolve, reject) => {
    resolve('Promise1  Resolved!');
});

const promise2 = new Promise((resolve, reject) => {
    resolve('Promise2  Resolved!');
});

const promise3 = new Promise((resolve, reject) => {
    resolve('Promise3  Resolved!');
});


Promise.all([promise1,promise2,promise3]).then((result)=>{
console.log(result);
})

//Output:  ["Promise1  Resolved!", "Promise2  Resolved!", "Promise3  Resolved!"]


Enter fullscreen mode Exit fullscreen mode

In the above example, we have 3 simple promises which are always resolved and they all return a single message.
By Using Promise.all we can run all promises in parallel, As soon as all the promises are executed .then method is called. .then will return an array of all the successful messages.

Thank you for your time. That's All folks

Top comments (0)