Writing a Purifier Closing a Promise
New in Angular and promises, but I realized I did this a lot:
this.myService.createFoo(data).subscribe(
(result: any) => {
resolve({success: true, data: result});
},
err => {
resolve({success: false, message: err});
});
this.myService.updateFoo(data).subscribe(
(result: any) => {
resolve({success: true, data: result});
},
err => {
resolve({success: false, message: err});
});
How do I rewrite the completion closure for my subscription method so that I don't have to repeat code like this ?. Thank!
source to share
One approach is to extract your callbacks into generic functions and simply pass them:
const successHandler = (data: any) => resolve({success: true, data });
const errorHandler = (message) => resolve({success: false, message });
this.myService.createFoo(data).subscribe(successHandler, errorHandler);
this.myService.updateFoo(data).subscribe(successHandler, errorHandler);
If you want to define them outside of the scope Promise
(which I assume is the code you posted inside), you can handle the handlers:
some-util-library.js
const handlers = resolve => ({
success: (data: any) => resolve({success: true, data }),
error: (message) => resolve({success: false, message })
});
export { handlers };
otherfile.js
import { handlers } from './some-util-library.js';
... other code
const { success, error } = handlers(resolve);
this.myService.createFoo(data).subscribe(success, error);
this.myService.updateFoo(data).subscribe(success, error);
source to share
I am assuming that you are trying to return a promise and that the code you posted is contained in a method that looks something like this:
create(): Promise<any> {
const data = 'whatever';
return new Promise<any>((resolve, reject) => {
this.myService.createFoo(data).subscribe(
(result: any) => {
resolve({ success: true, data: result });
},
err => {
resolve({ success: false, message: err });
});
});
}
If this is the case, rather than manually creating a promise, you can turn your Observable into a promise using an operator toPromise
. First you need to import it, if you haven't already:
import 'rxjs/add/operator/toPromise';
Then, by combining it with async
and await
, you can transform your code like this:
async create(): Promise<any> {
const data = 'whatever';
try {
const result = await this.myService.createFoo(data).toPromise();
return { success: true, data: result }
} catch (err) {
return { success: false, message: err };
}
}
source to share