Angular - Promise Explained with Code Example - Data Analytics (2022)

Angular - Promise Explained with Code Example - Data Analytics (1)

Promise, in Javascript, is a concept which allows the callee function to send back a promise (sort of assurance) to the caller function that it would, for sure, send back a resolution, be it a success or a failure at a little later point of time. The caller believes the callee if a promise is sent back, and, proceeds ahead with the program execution.

On a lighter note, the following comic strip represents the relationship between the caller and callee. As like the below, caller function can believe on callee function sending back Javascript promise object, which does result in the state of either resolution or a rejection (in case of errors).

Angular - Promise Explained with Code Example - Data Analytics (2)

Figure 1. Rest assured, promises are kept through resolution or rejection

In this post, you will learn about some of the following concepts in relation to promise concept vis-a-vis an angular app built with Angular 2.*, Angular 4.* and Angular 5.* versions:

  • Introduction to Promise
    • How to create a promise?
    • How to process a returned promise object?
    • What is promise chaining?
  • Promise with Angular Http Service
  • Promise with Angular HttpClient Service
  • Sample interview questions
  • Practice Test

Table of Contents

Introduction to Promise with Code Examples

Here is a detailed introduction of promise concept with the help of code examples wherever appropriate:

  • Allows asynchronous operations to happen; Caller can proceed ahead with program execution if callee function returned a promise object.
  • How to create Promise using new operator: The following represents the sample code of a function which creates a Promise object using new operator and return the same:
    function printHelloWithPromise(name) { let promise = new Promise(function(resolve, reject) { // In place of the code given below, one can call REST APIs // For errors, one can choose to reject the promise; // For successful processing, promise can be resolved // const responseVar = 1+1; if(responseVar == 2) { resolve("Success: " + name); } else { reject("Error: " + name); } }); return promise; }

    Note some of the following:

    • The result of code execution within promise could be processed appropriately to either resolve or reject the promise.
    • resolve method is used to resolve the promise in form of successful resolution
    • reject method is used to reject the promise if an error occurred
  • How to process a Promise object returned from callee function: The following represents the sample code for caller function processing the Promise object returned by the callee function:
    let greetingPromise = printHelloWithPromise("https://vitalflux.com");greetingPromise.then(function(resolveOutput) { console.log(resolveOutput);}, function(rejectOutput) { console.log(rejectOutput);});

    Note some of the following:

    • For resolution, function with resolveOutput is invoked
    • For error where the promise is rejected, function with rejectOutput value is processed.
  • What is Promise chaining?: The promise object can further be passed to another promise object which can then be passed to another promise object which could then choose to resolve or reject the promise. This process is called as chaining.

Promise & Angular Http Service

In this section, you will learn the usage of Promise with Angular Http service. The code given below works for Angular 2 and Angular 4 apps.

The following represents the code of a custom Angular Service. The code has an API namely getRx. The getRx API internally invokes a REST API call to get the prescription information from the server for a logged in user.

import {Http, Headers} from '@angular/http';import {Injectable} from '@angular/core';import {Rx} from './rx';import {Cookie} from 'ng2-cookies';@Injectable()export class RxService { private rxUrl = 'http://localhost:8080/rx'; constructor(private http: Http) { } getRx(): Promise<Rx[]> { let headers = new Headers({ 'Content-type': 'application/json', 'Authorization': 'Bearer ' + Cookie.get('access_token') }); return this.http.get(this.rxUrl, {headers: headers}) .toPromise() .then(res => res.json()) .catch(err => { return Promise.reject(err.json().error || 'Server error'); }); }}

Make a note of some of the following in above code:

  • The HTTP service get method returns an Observable object.
  • On an Observable object, RxJS toPromise() method is called which converts the observable to Promise object.
  • On the Promise object, the method then is invoked which returns the Promise<Rx[]>.

The code below represents the processing of callee method which returns Promise<Rx[]>.

export class RxListComponent implements OnInit { rxlist: Rx[]; errorMessage: string; constructor(private rxService: RxService, private router: Router) { this.errorMessage = ''; } ngOnInit(): void { this.getRx(); } getRx() { this.rxService.getRx() .then(rxlist => { this.rxlist = rxlist; if (this.rxlist.length === 0) { this.errorMessage = 'There are no prescriptions you have created so far!'; } }, error =&amp;gt; { this.router.navigateByUrl('/auth/login'); console.error('An error occurred in retrieving rx list, navigating to login: ', error); }); }}

Promise & Angular HttpClient Service

In this section, you will learn the usage of Promise with Angular HttpClient service. The code given below works for Angular 4.3 and Angular 5 apps. Note that HttpClient is the recommended way for communicating with remote APIs from Angular 5.* onwards.

Make a note of some of the following in the code given below:

  • API toPromise() is used to convert Observable response (HttpResponse<object>) object to Promise response object.
  • HttpHeaders instance is used to set the Authorization information in the outgoing interest.
  • Option ‘observe’: response makes sure entire Http response is returned in the response including data and headers information.
  • Promise.reject is used when promise state moves to rejected.
import {Http, Headers, RequestOptions} from '@angular/http';import {Injectable} from '@angular/core';import {Rx} from './rx';import {Observable} from 'rxjs/Observable';import {Cookie} from 'ng2-cookies';import {HttpClient, HttpHeaders, HttpResponse} from "@angular/common/http";@Injectable()export class RxService { private rxUrl = 'http://localhost:8080/rx'; constructor(private httpClient: HttpClient) { } getRx(): Promise<Rx[]> { return this.httpClient.get(this.rxUrl, {observe: 'response', headers: new HttpHeaders().set('Authorization', 'Bearer ' + Cookie.get('access_token'))}) .toPromise() .then(this.extractData) .catch(err => { return Promise.reject(err.error || 'Server error'); }); } extractData(res: HttpResponse<Object>) { var array = new Array(); var key, count = 0; for(key in res.body) { array.push(res.body[count++]); } return array; }}

Sample Interview Questions

  • What is a Promise in Javascript?
  • How to create and return a promise? Explain with a code example?
  • How is a returned promise object processed? Show with a code example?
  • Explain Http Get API implementation with Promise with a code example?
  • Explain HttpClient Get API implementation with Promise with a code example?
  • Explain the difference between Promise implementations for Http Get and HttpClient Get APIs?

Practice Test

Promise helps in achieving which of the following type of operations?

Correct!Wrong!

Which of the following is recommended service for communicating with remote server APIs from Angular 5.* onwards?

Correct!Wrong!

Angular Http or HttpClient Get API returns which of the following?

Correct!Wrong!

(Video) Promises in angular 2 example

Angular HttpClient forms part of which of the following library?

Correct!Wrong!

Which of the following are possible states of Promise execution?

Correct!Wrong!

(Video) Testing Promises in Angular - FakeAsync() - Part 1
(Video) Promises vs Observables - Angular (Tutorial #30)

Interview Questions - Promise & Angular

You did extremely well!!

You did reasonably well!!

Better luck next time!!

Further Reading

Summary

In this post, you learnt about some of the following:

  • Terminologies and concepts related with Promise concept in Javascript
  • How is Promise concept used in Angular vis-a-vis Angular 4/Angular 2 Http service and Angular 5 HttpClient service.
  • Sample interview questions
  • Practice tests to check your knowledge

Did you find this article useful? Do you have any questions about this article or understanding Promise and related concepts and terminologies vis-a-vis Angular 4/Angular 2 Http APIs and Angular 5 HttpClient APIs? Leave a comment and ask your questions and I shall do my best to address your queries.

  • Author
  • Recent Posts

Follow me

Ajitesh Kumar

I have been recently working in the area of Data analytics including Data Science and Machine Learning / Deep Learning. I am also passionate about different technologies including programming languages such as Java/JEE, Javascript, Python, R, Julia, etc, and technologies such as Blockchain, mobile computing, cloud-native technologies, application security, cloud computing platforms, big data, etc. For latest updates and blogs, follow us on Twitter. I would love to connect with you on Linkedin.

Check out my latest book titled as First Principles Thinking: Building winning products using first principles thinking

Follow me

Latest posts by Ajitesh Kumar (see all)

  • - September 2, 2022
  • - August 30, 2022
  • Google Colab: Read File from Local Drive - August 28, 2022
(Video) EP 11.3 - Angular / HTTP / HTTP with Promises

Angular - Promise Explained with Code Example - Data Analytics (5)

Ajitesh Kumar

I have been recently working in the area of Data analytics including Data Science and Machine Learning / Deep Learning. I am also passionate about different technologies including programming languages such as Java/JEE, Javascript, Python, R, Julia, etc, and technologies such as Blockchain, mobile computing, cloud-native technologies, application security, cloud computing platforms, big data, etc. For latest updates and blogs, follow us on Twitter. I would love to connect with you on Linkedin. Check out my latest book titled as First Principles Thinking: Building winning products using first principles thinking

FAQs

What is promise in angular with example? ›

What Is Promise in Angular? Promises in Angular provide an easy way to execute asynchronous functions that use callbacks, while emitting and completing (resolving or rejecting) one value at a time. When using an Angular Promise, you are enabled to emit a single event from the API.

What is difference between promise and Observable? ›

The biggest difference is that Promises won't change their value once they have been fulfilled. They can only emit (reject, resolve) a single value. On the other hand, observables can emit multiple results. The subscriber will be receiving results until the observer is completed or unsubscribed from.

Can we use promise with Observable in angular? ›

Both observables and promises help us work with asynchronous functionality in JavaScript. Promises deal with one asynchronous event at a time, while observables handle a sequence of asynchronous events over a period of time. Emit multiple values over a period of time. Emit a single value at a time.

How do I write a promise function in TypeScript? ›

The following steps include:
  1. Step 1: Create package. json file with { }.
  2. Step 2: Call npm install –save @types/es6-promise. ...
  3. Step 3: Then, call tsc –init. ...
  4. Step 4: Now, we can use promise in typescript file using var x: Promise;
  5. Step 5: Execute tsc -p to compile the project or program you created.
25 Mar 2022

What is promise and why do we use it? ›

Promises are used to handle asynchronous operations in JavaScript. They are easy to manage when dealing with multiple asynchronous operations where callbacks can create callback hell leading to unmanageable code.

How do you write a promise in Angular 8? ›

This an example of a simple promise object that returns I promise to return this after 1 second! var promise = new Promise(function(resolve, reject) { setTimeout(function() { resolve('I promise to return this after 1 second!' ); }, 1000); }); promise. then(function(value) { console.

Which is faster promise or observable? ›

While a Promise starts immediately, an Observable only starts if you subscribe to it. This is why Observables are called lazy.

Which is better promise or async await? ›

Using Async/Await makes it easier to read and understand the flow of the program as compared to promise chains.

Are promises async? ›

A promise is used to handle the asynchronous result of an operation. JavaScript is designed to not wait for an asynchronous block of code to completely execute before other synchronous parts of the code can run. With Promises, we can defer the execution of a code block until an async request is completed.

Can we use Promise in TypeScript? ›

The promise in TypeScript is used to make asynchronous programming. The promise can be used when we want to handle multiple tasks at the same time. By the use of TypeScript promise, we can skip the current operation and move to the next line of the code.

What is Promise in angular TypeScript? ›

A promise is a TypeScript object which is used to write asynchronous programs. A promise is always a better choice when it comes to managing multiple asynchronous operations, error handling and better code readability. We know what does synchronous and asynchronous programs are.

How do you read a Promise value in TypeScript? ›

To access the value of a promise in TypeScript, call the then() method on the promise, e.g. p. then(value => console. log(value)) . The then() method takes a function, which is passed the resolved value as a parameter.

Can Promise be Cancelled? ›

Promises have settled (hah) and it appears like it will never be possible to cancel a (pending) promise. Instead, there is a cross-platform (Node, Browsers etc) cancellation primitive as part of WHATWG (a standards body that also builds HTML) called AbortController .

Is promises are more advanced than observables? ›

Additionally, Observables are "cancellable" and can emit multiple events whereas Promises reject/resolve a single event. While Observables are seemingly "better" for any use case, there are times where a Promise is more appropriate, especially when your application is async by nature.

Can we use async await in Angular? ›

Using Async/Await in Angular

One of the best improvements in JavaScript is the Async/Await feature introduced in the ECMAScript 7. Basically, Async/Await works on top of Promise and allows you to write async code in a synchronous manner. It simplifies the code and makes the flow and logic more understandable.

How does promise work? ›

The Promise constructor takes a function (an executor) that will be executed immediately and passes in two functions: resolve , which must be called when the Promise is resolved (passing a result), and reject , when it is rejected (passing an error).

What is the difference between promise and callback? ›

A callback function is passed as an argument to another function whereas Promise is something that is achieved or completed in the future. In JavaScript, a promise is an object and we use the promise constructor to initialize a promise.

Why are promises better than callbacks? ›

The superiority of promises over callbacks is all about trust and control. Let me explain. We generally need to use callbacks (or promises) when there is a slow process (that's usually IO-related) that we need to perform without blocking the main program process.

What is a Promise explain it layman's terms? ›

A promise is a commitment by someone to do or not do something. As a noun promise means a declaration assuring that one will or will not do something. As a verb it means to commit oneself by a promise to do or give. It can also mean a capacity for good, similar to a value that is to be realized in the near future.

How do I return a Promise object? ›

resolve() method in JS returns a Promise object that is resolved with a given value. Any of the three things can happened: If the value is a promise then promise is returned. If the value has a “then” attached to the promise, then the returned promise will follow that “then” to till the final state.

How do you Promise in Angular 10? ›

Promises can be executed by calling the then() and catch() methods. The then() method takes two callback functions as parameters and is invoked when a promise is either resolved or rejected. The catch() method takes one callback function and is invoked when an error occurs.

Is Observable lazy? ›

Observables are "lazy", meaning if no one is listening, nothing happens.

Is Observable async? ›

A common misconception in Angular development is regarding whether observables are synchronous or asynchronous. A lot of (even experienced Angular developers) think that observables are async, but the truth is that they can be… Both synchronous and asynchronous.

Is Angular synchronous or asynchronous? ›

Angular makes use of observables as an interface to handle a variety of common asynchronous operations. For example: The HTTP module uses observables to handle AJAX requests and responses.

Can we use async await without promise? ›

This rule applies when the await operator is used on a non-Promise value. await operator pauses the execution of the current async function until the operand Promise is resolved.

Is promise synchronous or asynchronous? ›

In JavaScript, promises are special objects that help you perform asynchronous operations. You can create a promise using the Promise constructor. You need to pass an executor function to it. In the executor function, you define what you want to do when a promise returns successfully or when it throws an error.

What is better than promises? ›

"Efforts Are Better Than Promises."

Can you await a promise? ›

async and await

Inside an async function, you can use the await keyword before a call to a function that returns a promise. This makes the code wait at that point until the promise is settled, at which point the fulfilled value of the promise is treated as a return value, or the rejected value is thrown.

Is promise all synchronous? ›

If an empty iterable is passed, then the promise returned by this method is fulfilled synchronously. The fulfilled value is an empty array. If a nonempty iterable is passed, and all of the promises fulfill, or are not promises, then the promise returned by this method is fulfilled asynchronously.

Does promise run on main thread? ›

The callback that processes the response from your created Promises still runs on your single main thread. Promises do, however, allow you to spawn asynchronous tasks, such as file I/O or making an HTTP request which runs outside of your code.

What is Promise in TypeScript? ›

The promise in TypeScript is used to make asynchronous programming. The promise can be used when we want to handle multiple tasks at the same time. By the use of TypeScript promise, we can skip the current operation and move to the next line of the code.

What is HTTP request Promise? ›

The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.

What is async and Await in Angular? ›

Async/Await. Promise is an operation which is guaranteed to complete its execution at some point in the future. Async/Await is built on top of promises. They are syntactic sugar for promises, making the code look more synchronous. Error handling is done using .then() and catch() methods.

What is callback in Angular? ›

Callback function is a function which is passed to a function as parameter and is executed when the outer function is completed. Callbacks are a feature of JavaScript not particularly angularjs. Its a way to send a function as a parameter to the callee so that the callee call that function once the task is finished.

How do promises work? ›

A promise is an object that may produce a single value some time in the future : either a resolved value, or a reason that it's not resolved (e.g., a network error occurred). A promise may be in one of 3 possible states: fulfilled, rejected, or pending.

Can you await a promise? ›

async and await

Inside an async function, you can use the await keyword before a call to a function that returns a promise. This makes the code wait at that point until the promise is settled, at which point the fulfilled value of the promise is treated as a return value, or the rejected value is thrown.

How do you read a promise value in TypeScript? ›

To access the value of a promise in TypeScript, call the then() method on the promise, e.g. p. then(value => console. log(value)) . The then() method takes a function, which is passed the resolved value as a parameter.

How do you get data from promises? ›

Define an async function. Use the await operator to await the promise. Assign the result of using the await operator to a variable.

How do I get data from API promise? ›

Summary
  1. The Fetch API allows you to asynchronously request for a resource.
  2. Use the fetch() method to return a promise that resolves into a Response object. ...
  3. Use the status and statusText properties of the Response object to get the status and status text of the response.

Are promises async? ›

A promise is used to handle the asynchronous result of an operation. JavaScript is designed to not wait for an asynchronous block of code to completely execute before other synchronous parts of the code can run. With Promises, we can defer the execution of a code block until an async request is completed.

Which is better Promise or async await? ›

Using Async/Await makes it easier to read and understand the flow of the program as compared to promise chains.

Is Angular synchronous or asynchronous? ›

Angular makes use of observables as an interface to handle a variety of common asynchronous operations. For example: The HTTP module uses observables to handle AJAX requests and responses.

Is Observable asynchronous? ›

An observable produces values over time. An array is created as a static set of values. In a sense, observables are asynchronous where arrays are synchronous. In the following examples, → implies asynchronous value delivery.

What is Angular data binding? ›

Data binding in AngularJS is the synchronization between the model and the view. When data in the model changes, the view reflects the change, and when data in the view changes, the model is updated as well.

Can we pass function from parent to child in Angular? ›

In your child component, add an @Input variable to bind the parent component's passed function: @Input() callbackFunction: (args: any) => void; Make sure that the signature definition of your @Input() function matches the myCallbackFunction that you defined in the parent component.

What is an observable in Angular? ›

Observables provide support for data sharing between publishers and subscribers in an angular application. It is referred to as a better technique for event handling, asynchronous programming, and handling multiple values as compared to techniques like promises.

Videos

1. explained promise with resolve and reject in Angular
(keps code fun)
2. Angular 11 - Observables VS Promise in Angular 11 #tutorial 32
(DevCodes)
3. Observable in Angular 13 | auto refresh after database update | communicate components using service
(Nihira Techiees)
4. Promises vs Observables in 2 minutes
(Irek Mirgaleev)
5. Angular 5 Promises Tutorial
(Steve Buonincontri)
6. Angular Services with http promise | Angular tutorial
(DWBIADDA VIDEOS)

Top Articles

You might also like

Latest Posts

Article information

Author: Aracelis Kilback

Last Updated: 12/02/2022

Views: 6087

Rating: 4.3 / 5 (44 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Aracelis Kilback

Birthday: 1994-11-22

Address: Apt. 895 30151 Green Plain, Lake Mariela, RI 98141

Phone: +5992291857476

Job: Legal Officer

Hobby: LARPing, role-playing games, Slacklining, Reading, Inline skating, Brazilian jiu-jitsu, Dance

Introduction: My name is Aracelis Kilback, I am a nice, gentle, agreeable, joyous, attractive, combative, gifted person who loves writing and wants to share my knowledge and understanding with you.