Promises
In JavaScript, asynchronous operations are handled through promises. When dealing with several asynchronous activities, where callbacks might lead to callback hell and incomprehensible code, they are simple to manage.
Events or callback functions were being used before the promises, but they provided limited functionality and resulted in unmanageable code.
The callback hell that would result from having several callback functions would make the code unmanageable. Additionally, managing several callbacks at once is difficult for any user.
For handling asynchronous actions in the simplest way possible, promises are the best option. In comparison to callbacks and events, they can manage many asynchronous activities with ease and offer better error handling. In other words, promises are the best option for managing several callbacks concurrently, preventing the undesirable callback hell scenario. Promise to give users a greater chance to interpret code more effectively and efficiently, especially when such regulation is being utilized to implement several asynchronous actions.
if you want to learn more about the differences in observer vs promise, you can refer here
- Benefits of Promises
- Improves Code Readability
- Better handling of asynchronous operations
- Better flow of control definition in asynchronous logic
- Better Error Handling
- A Promise has four states:
- fulfilled: Action related to the promises succeeded
- rejected: Action related to the promises failed
- pending: Promise are still pending i.e. not fulfilled or rejected yet
- settled: Promises have been fulfilled or rejected
- A promise can be created using the Promise constructor.
Example-:
var promise = new Promise(function(resolve, reject){
//do something
});
- Parameters
- The callback function is the only argument given to the promise constructor(and that callback function is also referred to as an anonymous function too).
- The callback function takes two arguments, resolve and reject
- If everything went successfully, do operations inside the callback function and then call resolve.
- If desired operations do not go well then call reject.
Promise.resolve()
A provided value can be “resolved” to a Promise using the Promise.resolve() method. If the value is a promise, that promise is returned; otherwise, the returned promise would be fulfilled with the value if the value is a then able, in which case Promise.resolve() will run the then() method with two callbacks it has prepared.
The promise that fulfills a non-then able value is created by flattening multiple levels of promise-like objects (such as promises that fulfill other promises that fulfill something) into a single layer.
Syntax- Promise.resolve(value)
Example-:
const promise1 = Promise.resolve(730);
promise1.then((value) => {
console.log(value);
// expected output: 730
});
Promise.reject()
The Promise.reject() method returns a Promise object rejected for a given reason.
Syntax- Promise.reject(reason)
Example-:
function resolved(result) {
console.log('Resolved');
}
function rejected(result) {
console.error(result);
}
Promise.reject(new Error('fail')).then(resolved, rejected);
// expected output: Error: fail
Promise.all()
An iterable promise is passed into the Promise.all() method, which returns a single promise resolved to an array of the promise’s results. When every promise in the input has been completed or if there are no promise in the input iterable, the promises that were returned will be fulfilled. Upon any of the input promises being rejected or a non-promises throwing an error, it rejects immediately and will reject with this initial rejection message/error.
Syntax- Promise.all(iterable)
Example-:
const promise1 = Promise.resolve(5);
const promise2 = 65;
const promise3 = new Promise((resolve, reject) => {
setTimeout(resolve, 100, 'abc');
});
Promise.all([promise1, promise2, promise3]).then((values) => {
console.log(values);
});
// expected output: Array [5, 65, "abc"]
Promise.race()
As soon as one of the promise in an iterable fulfills or rejects, the Promise.race() method returns a promise with the value or reason from that promise.
Syntax- Promise.race(iterable)
Example-:
const promise1 = new Promise((resolve, reject) => {
setTimeout(resolve, 500, 'abc');
});
const promise2 = new Promise((resolve, reject) => {
setTimeout(resolve, 100, 'def');
});
Promise.race([promise1, promise2]).then((value) => {
console.log(value);
// Both resolve, but promise2 is faster
});
// expected output: "two"
Promise Consumers
Promise can be consumed by registering functions using the .then and .catch methods.
- then()
When a promise is accepted or declined, the function then() is called. It might also be described as a job that takes information from a promisesand successfully carries it out.
Parameters:
then() method takes two functions as parameters.
- The first function is executed if the promises is resolved and a result is received.
- The second function is executed if the promises is rejected and an error is received. (It is optional and there is a better way to handle error using the .catch() method
Syntax-
.then(function(result){
//handle success
}, function(error){
//handle error
})
Example-:
var promise = new Promise(function(resolve, reject) {
resolve('it is resolved');
})
promise
.then(function(successMessage) {
//success handler function is invoked
console.log(successMessage);
}, function(errorMessage) {
console.log(errorMessage);
})
2. catch()
When a promises is either refused or an execution problem occurs, the catch() method is called. Whenever there is a probability of receiving an error at any phase, it is used as an error handler.
Parameters:
catch() method takes one function as a parameter.
- Function to handle errors or promises rejections.(.catch() method internally calls .then(null, error handler), i.e. .catch() is just a shorthand for .then(null, error handler) )
Syntax:
.catch(function(error){
//handle error
})
Example-:
var promise = new Promise(function(resolve, reject) {
reject('Promise Rejected')
})
promise
.then(function(successMessage) {
console.log(successMessage);
})
.catch(function(errorMessage) {
//error handler function is invoked
console.log(errorMessage);
});
Conclusion
In this blog, we have learned about the promises and functioning of promises in javascript with some basic examples.
Reference
https://codecraft.tv/courses/angular/es6-typescript/promise/