A promises
is a javascript object that allows you to make asynchronous calls.
It produces a value when async operation completes successfully or produces an error if it doesn't complete.
You can create promise using constructor:
let promise = new Promise (function(resolve, reject){
})
Executor function takes two arguements:-
resolve
- indicate successful completionreject
- indicates an error
The Promise Object should be capable of informing consumers when execution has been started, completed in returned with an error.
- State
pending
- when execution function startsfulfilled
- when promise resolved successfullyrejected
- when the promise rejects
- result
undefined
- initially when state value is pendingvalue
- when promise is resolvederror
- when the promise is rejected
A promise that is either resolved or rejected are settled.
Three important handler methods:
then()
catch()
finally()
These methods helps us create a link between executor and consumer.
It is used to let consumer know outcome of promise. It accept two arguements:
- result
- error
E.g.
promise.then(
(result) => {
console.log(result);
},
(error) => {
console.log(error);
}
);
To handle error(rejections) from Promises.
It's better syntax to handle error than handling it with .then()
E.g.
promise.catch(function(error){
console.log(error);
});
The funally() handler method performs cleanups like stopping a loader, closing a live connection and so on.
Irrespective of whether promise resolve or rejects, the finally() method will run.
E.g.
promise.finally( () => {
console.log('Promise Settled');
}).then((result) => {
console.log({result});
});
Important point to note,
The finally() method passes through result or error to the next handler which can call a .then() or .catch() again.