Thomas Burleson
Feb 23, 2017 · 1 min read

Viktor,

Here is a refactored service that IMO is more clear:

class PurchaseService {
inProgress = false;

constructor(
private backend: PurchaseBackend,
private messages: Messages) { }

order(sku: string, qty: number): void {
if (this.inProgress) {
this.messages.error("Already purchasing an item");
return;
}

this.backend
.checkAvailability(sku, qty)
.then(this.orderFromBackEnd.bind(this))
.then(this.announcePurchase.bind(this));
}

orderFromBackEnd(enoughQuantity:boolean) {
let finishProgress = () => this.inProgress = false;
this.inProgress = enoughQuantity;
return !enoughQuantity ? false :
this.backend.order(sku,qty).then(finishProgress);
}

announcePurchase((success: boolean) => {
if (success) this.messages.success("Your purchase succeeded!");
else this.messages.error("Your purchase failed!");
}
}
    Thomas Burleson

    Written by

    Solution Architect with passion for React, Angular, UX, and great software products. Formerly Google Team Lead for AngularJS Material, @angular/flex-layout, …