Promise(an object):
Represents an eventual outcome of an asynchronous operation.
It has three states:
- Pending: initial states - operation has not been completed yet. The operation is running.
- Fulfilled: the operation has been completed and the promise has a resolved value.
- Rejected: the operation has failed due to reasons or errors.
How to create or construct a promised object?
To create a promise object we need a new keyword and a promise constructor method.
const executorFunction = (resolve, reject) => {};'lion-baby' : "cub"
const myFirstPromise = new Promise(executorFunction);
executorFunction:
The promise constructor method takes a function as a parameter called the executor function. This executor function runs automatically when the constructor is called.
This executor function has two function parameters such as resolve() and reject().
How does Promise work?
When the Promise constructor runs, then the executor function will run automatically. Then JavaScript will run a resolve function and will check some conditions. If the conditions are true, then we can invoke the resolve() method and we can show anything within it.
If any condition is not true, then javascript will run the reject function and then we can invoke the reject method and we can show anything within it.
Example :
Without capturing the resolved value:
function myPromise(control) {return new Promise((resolve, reject) => {setTimeout(function () {if (control) {resolve();} else {reject();}}, 3000);});}myPromise(true).then(function () {console.log("Promise has been resolved");}).catch(function () {console.log("Promise failed");}).finally(function () {console.log("Promise running");});
With Capturing resolved value (1):
function myPromise(control) { return new Promise((resolve, reject) => { setTimeout(function () { if (control) { resolve("Promise has been resolved"); } else { reject("Promise failed"); } }, 3000); }); } myPromise(true) .then(function (result) { console.log(result); }) .catch(function (error) { console.log(error); }) .finally(function () { console.log("Promise running"); }); // finally() will run whether the promise resolved or not.
With Capturing resolved value (2):
let val = false;const promised = new Promise(function (resolve, reject) {if (val === true) {resolve("from resolve");}if (val === false) {reject("from reject");}}).then(function (result) {console.log(result);}).catch(function (error) {console.log(error);});
Post a Comment