A JavaScript standard class Promise is asynchronous action that might get completed at a certain point and produce a success or failure. It notifies when the value is available.
How to create a promise?
Quick and easy way to do it to call Promise.resolve to create a promise and get a value wrapped in a promise. You can also create a constructor.
If it’s a promise then you get the value returned and if not, it creates a new promise with the passed value as it’s result.
After that you can use then method to get the result of the promise. then method registers a callback function which gets called when the promise resolves and at the end it produces a value.
A promise is a kinda assurance that you’ll get some value in the future.
Example
let greet = Promise.resolve("hello");
greet.then(value => console.log(`Saying ${value}`));
// "Saying hello"
Promise states
A pending state is an initial state which indicates that the result is still pending, it’s not fulfilled or rejected. Other two states are fulfilled (operation completed successfully) and rejected (operation failed).
Can you add multiple callbacks to a single promise?
Yes, you can add multiple callbacks to a single promise.
In fact, you can add then even after the promise has been completed. All callbacks will be called.
then method can return another promise and the value the handler function returns and the loop continues. So, if the handler function returns another promise then it’s going to wait till that promise resolves a value.
Promise as a constructor
We can also use Promise as a constructor which expects a function as an argument.
A simple example
const greet = new Promise((resolve, reject) => {
resolve('hello');
});
greet.then((value) => {
console.log(`Saying ${value} again!`);
});
// "Saying hello again!"
Promise constructor with setTimeout
let promiseEx = new Promise(function(resolve, reject) {
setTimeout(function() {
resolve("Promise request resolved!");
}, 1000);
});
promiseEx.then(function(value) {
console.log(value);
});
//"Promise request resolved!"
constructor examples functions promise states