javascript promise
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).
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:
Here is a detailed introduction of promise concept with the help of code examples wherever appropriate:
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:
let greetingPromise = printHelloWithPromise("https://vitalflux.com"); greetingPromise.then(function(resolveOutput) { console.log(resolveOutput); }, function(rejectOutput) { console.log(rejectOutput); });
Note some of the following:
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 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 =&gt; { this.router.navigateByUrl('/auth/login'); console.error('An error occurred in retrieving rx list, navigating to login: ', error); }); } }
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:
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; } }
Share your Results:
In this post, you learnt about some of the following:
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.
Last updated: 28th Aug, 2024 Confusion among data scientists regarding ROC Curve and AUC often…
Last updated: 27th Aug, 2024 Classification models are used in classification problems to predict the…
Last updated: 26th August, 2024 In this blog post, we will discuss the concepts of…
Last updated: 25th August, 2024 In machine learning, model complexity and overfitting are related in…
Last updated: 24th August, 2024 Model parallelism and data parallelism are two strategies used to…
Last updated: 24th August, 2024 The performance of the machine learning models on unseen datasets…