What is a Promise?
The Promise object represents the eventual completion (or failure) of an operation and its resulting value. It is used very frequently with asynchronous operations in JavaScript. In layman's terms, it provides an acknowledgment to the operation performed. If the action is a success (or pass), then it will resolve the promise else it will reject the promise.
Syntax
- new Promise( function(resolve, reject) { ... } )
Promise constructor takes a function as an argument which, in-turn, takes 2 arguments - resolve and reject. The function calls immediately the resolve or the reject handler once the action performed by the promise comes to a conclusion, i.e., a success or failure.
The handlers are called using the following syntax.
- Promise.then(function(){...for resolve...}).catch(function(){...for reject...})
Example
- let promiseToCode = new Promise(function(resolve, reject) {
-
-
- var doICode = true;
- if (doICode) {
- resolve("coding");
- } else {
- reject("sleeping");
- }
- })
- promiseToCode.then(function(fromResolve) {
- console.log("I am " + fromResolve);
- }).catch(function(fromReject) {
- console.log("I am " + fromReject)
- })
Explanation
This is a very simple promise. In this promise, based on the condition of the promise, it will log the message.
If the "doICode" variable in the promise is made true, then it will print "I am coding", else it will print "I am sleeping".
Please feel free to give your feedback.