What are Promises in Angular? Syntax, Examples, Future
Updated on Oct 24, 2024 | 9 min read | 20.5k views
Share:
For working professionals
For fresh graduates
More
Updated on Oct 24, 2024 | 9 min read | 20.5k views
Share:
Table of Contents
JavaScript is single-threaded which means it is inherently synchronous. Thus, code runs line by line on the processor. But, suppose we have a functionality that needs to wait for something such as fetching a file, any web results, or other activity like this, in that case, making the wait to the application until the previous operation is finished is not efficient and it is considered as a major point of failure in any such application. To overcome this JavaScript, we can apply asynchronous behavior.
After the execution, we would want to do different operations with the data gotten from these async functions as all our synchronous code runs before async ones. JavaScript provides three mechanisms for doing that:
We can use callback functions but there is a major drawback of using callbacks in a situation where we need to carry out a series of async operations with the next operation dependent on data from the previous one.
To do this with callbacks we end up nesting callbacks inside callbacks, making our code very hard to read and error handling becomes a nightmare.
A promise in angular is a JavaScript object which produces a value after an async operation is executed successfully. If the operation does not execute successfully, then it generates an error.
A promise in angular is a class-based object, it is created using the new keyword and its constructor function. It contains different types of methods that give sour objects some power.
A promise in Angular is defined by passing a callback function also known as the executor function or executor code as an argument to the Promise constructor. The executor function usually takes two arguments: resolve and reject.
An async operation is defined inside the executor function and intended result or error if any occurred is handled by the resolve and reject handlers respectively.
Sign up for a Master of Science in Computer Science from LJMU and master programming skills taught by industry experts.
Here below is the syntax:
const myPromise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('this is a promise');
}, 300);
});
myPromise.then((value) => {
console.log(value);
// expected output: "this is a promise"
});
console.log(promise1);
// expected output: [object Promise]
Promise objects have a .then and a .catch methods which handle fulfilled results and errors if any occurred. They receive the outcome of async operations as data or error from the resolve and reject handler in the promise constructor.
Learn more about what is promise in Angular by participating in a Full Stack Software Development Bootcamp.
Also, Promises in Angular has these states:
A promise in Angular is said to be settled if it is either fulfilled or rejected. It cannot be in pending state.
.then
.then method runs immediately after the promise has been fulfilled or after resolve is called.
.then takes a callback function which receives the result when resolve is called. Ie. .then(function). The callback function inside .then takes result as an argument. Result is the value that we passed on to resolve as an argument when calling it. Ie. Resolve(value)
.catch
.catch runs immediately after reject(error) executed by the executor. That is after the promise has been rejected
.finally
The finally handler runs after the promise is settled. Settled means that the promise is either fulfilled or rejected. Whether the promise was fulfilled or rejected. Finally is always going to run. It does not process a promise but rather finalizes everything after the previous operations have been completed.
Now, we know that .then and .catch methods returns promises hence they can be chained.
To demonstrate the use of Promises in angular let us see an example using Promises:
let
promise = new Promise((resolve, reject)=>{
setTimeout(()=>{
let count = 5
if(count == 5){
resolve("done")
}else{
reject(new Error("Ooops something went wrong))
}
}, 2000)
} )
Promise
.then((result)=>{
console.log(result)
})
.catch((error)=>{
console.log(error)
})
.finally(()=>{
console.log("Everything is finalized")
})
Output:
Done
Everything is finalized
Solution: The conditional if statement evaluates to true because count = = 5. resolve(done) is then called and the value “done” is passed onto .then as a result. Hence “done” is logged onto the console. .finally is then executed and logs “Everything is finalized” to the console.
There is a prevailing need to execute two or more asynchronous operations next to next sequentially, where each next operation starts when the previous operation succeeds, with the result from the prior operation. We manage this by designing a promise chain.
In other words, after producing code performs a task and gets the result, we usually want to do something different with that result. But we cannot directly access that result. We have to use .then method. The .then method returns a new promise, different from the original promise:
const myPromise = doSomeAction();
const myPromise2 = promise.then(succeedCallback, failedCallback);
This second promise(myPromise2) represents the completion of doSomeAction as well as the completion of succeedCallback and failedCallback we passed in, which can be other async functions returning a promise. When it happens, any callbacks added to myPromise2 get in line behind the promise returned by either succeedCallback or failedCallback.
Basically, each promise in angular represents the completion of another async step in the chain of promises.
For example:
taskOne()
.then(function (result) {
return taskTwo(result);
})
.then(function (newResult) {
return taskThree(newResult);
})
.then(function (lastResult) {
console.log(`Receive the last result: ${lastResult}`);
})
.catch(failureCallback);
Chaining After a Catch:
After catching an error, it is also possible to chain. That means .catch method is useful to achieve new actions even after an action failed in chain, we can accomplish remaining actions without any error.
For example:
new Promise((resolve, reject) => {
console.log("Start");
resolve();
})
.then(() => {
throw new Error("Something has failed");
console.log("Do this action1");
})
.catch(() => {
console.error("Do this action2");
})
.then(() => {
console.log("Do this action compulsory without looking what happened at previous");
});
Output:
Start
Do this action2
Do this action compulsory without looking what happened at previous
Here we are going to learn to define our Promise class myPromise:
Following properties are defined in constructor:
A promise in angular is executed very rapidly. It executes as soon as it is created, that way our promise callback function will be called inside the constructor with the methods - reject and resolve. And these methods are passed as parameters to the function.
Below is the example of Promise definition:
const STATE = {
PENDING:’PENDING’,
FULFILLED:’FULFILLED’,
REJECTED:’REJECTED’,
}
class myPromise{
constructor(callback){
//Initial state of Promise is empty
this.state = STATE.PENDING;
this.value = undefined;
this.handlers = [];
//Invoke callback by passing the _resolve and _reject functions of our class
try{
callback(this._resolve, this._reject);
}catch(err){
this._reject(err)
}
}
_resolve = (value) => {}
_reject = (error) => {}
.then(onSuccess, onFailure){}
.catch(onFailure){}
.finally(callback){}
}
Promises play a significant role in the Angular framework and because of concepts of ES6, importance of Promises is going to increase in JavaScript in the future. Thus, it can further be called a fundamental component of modern-day JavaScript.
Promises in Angular are the ideal choice for managing async operations in a simple manner. They can support better error handling than callbacks and events in Angular. Thus, we can avoid undesired situations like callback hell.
Promises in angular do provide a better chance for a user to read and understand the code in a more simple and efficient manner especially when that particular code is used for implementing multiple asynchronous operations. Because of all these reasons, Promises will be used on large scale in ale in Angular.
Angular promises are a placeholder holding the result of an async operation. If the operation completes successfully, then the promise fulfills with the operation value, but if the operation fails, the promise rejects and becomes the reason for the failure.
Angular promises can also build chains, which are valuable in handling multiple inter dependent async operations.
There is a lot more to the angular promises than then(), catch(), finally() methods which are the instance methods and chaining of promises. There are static methods as well as instance methods in the promises in Angular. upGrad Executive PG Programme in Full Stack Development from IIITB will comprehensively guide you in mastering programming and development.
Boost your software engineering skills with our top programs. Explore the courses below to find the right fit
Master in-demand software skills with our specialized courses. Explore your options below to upskill today
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
India’s #1 Tech University
Executive PG Certification in AI-Powered Full Stack Development
77%
seats filled
Top Resources