JavaScript has a special class called Promise. In order to create a promise, you’ll have to create an instance of the promise class. The promise constructor needs only a single argument which is a function (though you can add two arguments as well). The promise needs to be created with the function. The function is invoked live in real time when we create the promise. The function takes in two arguments : resolve and reject. Both of these arguments are also functions.
This is how the code template should look like :
const aStarterPromise = new Promise(function (resolve, reject) {
// your code here
});
Initially the promise is in pending state (i.e., if you don’t give any instructions to it). The resolve argument in the above code is used to activate the promise to a fulfilled or resolved state. The reject argument is used to write another function to convert the promise to a rejected state or status.
So overall, promises have three states: pending by default, resolve and reject. If you write the resolve code, it’ll resolve the promise and if you write the reject code, it’ll calculate whether to resolve or reject the promise and display the result accordingly.
Note that both resolved and rejected state cannot be changed once they are executed. Further, we have to use the then method in order to execute a promise. Here’s how :
const createPromise = new Promise(function (resolve, reject) {
resolve("Print this line");
});
createPromise.then(function (value) {
console.log(value);
});
So, promises are used to work with asynchronous JavaScript functions.
Let’s now look at an example of a JavaScript Promise which works asynchronously using both the resolve and reject arguments and returns the output after 2 seconds :
function numSquare(number) {
const promise = new Promise(function (resolve, reject) {
setTimeout(function () {
if (typeof number !== "number") {
return reject(new Error("Number is Expected"));
}
const result = number * number;
resolve(result);
}, 2000);
});
return promise;
}
numSquare(4).then(
(value) => {
console.log("Rendered Successfully: " + value);
},
(reason) => {
console.log("Error: " + reason);
}
);