DEV Community

Jaisurya
Jaisurya

Posted on

JavaScript Promises

A promise in JavaScript is an object that is used to represent the eventual completion or failure of an asynchronous operation.

With the help of promise in JavaScript, users can handle asynchronous operations in a more manageable and readable manner, if we compare it with traditional callbacks.

States of Promise

There are three states of Promise in JavaScript:

Pending: It is the initial phase, which represents that the asynchronous operations are still in progress.

Fullfilled: It indicates that the asynchronous operations has been completed successfully.

Rejected: It indicates that the operation has failed.

Syntax

The syntax of JavaScript promises is as follows:

let promise = new Promise(function(resolve, reject){
   //code to be executed
});
Enter fullscreen mode Exit fullscreen mode

Parameters

**resolve: **It marks the promise as fulfilled and provides a result.

**reject: **It marks the promise as rejected with an error.

Example

const myPromise = Promise.resolve("Hello, Welcome to Dev Community!");
myPromise.then(message => {
   console.log(message);
});

//Output: Hello, Welcome to Dev Community!

Enter fullscreen mode Exit fullscreen mode

Top comments (0)