Promises are used to handle asynchronous operations in javascript. With promises, we can defer the execution of a code block until an async request is completed. It is also used to find out if the asynchronous operation is successfully completed or not.
Promises can produce a single value which is either a resolved value or a rejected value.
const promise = new Promise((resolve, reject) => { // code execution if (success) { resolve(value); } else { reject(error); } }); promise.then((onFulfilled) => { console.log(onFulfilled); }) .catch((onRejected) => { console.log(onRejected); }) .finally(() => { render(); });
The Promise functions take and accept functions resolve() and reject() as an argument.
When the promise returns successfully, the resolve() function is called. and reject() function is called when an error occurs.
1. then() method
To get the value of a promise when it’s fulfilled, you call the then()
method of the promise object.
promise.then(onFulfilled,onRejected);
then()
the method accepts two callback functions: onFulfilled
and onRejected
.
then()
method calls the onFulfilled()
with a value, if the promise is fulfilled or the onRejected()
with an error if the promise is rejected.
Note: both onFulfilled
and onRejected
arguments are optional.
2. catch() method
If you want to get the error only when the state of the promise is rejected, you can use the catch()
method of the Promise
object:
promise.catch(onRejected);
3.finally() method
finally() method invoked when you want to execute the same piece of code whether the promise is fulfilled or rejected.
In this article, we have to show Create and Used PIPE in angular
In this article, we have to show Create and Used PIPE in angular
In this article, we have to show Create and Used PIPE in angular