My journey with JavaScript Promises has just begun, and I'm certain that there are better ways to handle them. Could you share some best practices for dealing with JavaScript Promises in the context of Angular 2?
Below is my Promise implementation used for authentication:
authenticate(user: Object): Promise<any> {
return new Promise((resolve, reject) => {
let body = JSON.stringify({ email: user['email'], password: user['passwords']['password'], repeatPassword: user['passwords']['repeatPassword'] });
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post(`${this.webApiService.webServiceAddressIp}/users/register`, body, options)
.subscribe((response: Response) => {
// login successful if there's a jwt token in the response
console.log("worked");
let user = response.json();
if (user && user.token) {
this.setSession(user.token);
}
return user;
}
, (error: any) => {
console.log("xxxxxxerror");
return error;
});
/*() => {
});*/
});
Here is an excerpt from my Angular 2 component TypeScript code where Promise errors are not being caught effectively:
this.authenticationService.authenticate(values).then((val: string) => {
console.log("done");
}).catch((err) => {
// Re-throw the error as a higher-level error.
// We will include the message from the lower-level
// error as part of the error message for this error.
console.log('11111');
})
.catch((err) => {
// In here we will get the higher-level error.
console.log("22222");
});
For instance, when the web API server is unavailable, ERR_CONNECTION_REFUSED errors are not handled properly within the TypeScript component. It would be ideal to inform the user about the connection issue.