What is a 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., 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) {
- //logic to be used in the promise
- //based on the output or result the resolve/reject will get called
- 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.
Join the conversation! Your thoughts help the community grow.