Thomas Burleson
Feb 23, 2017 · 1 min read

Actually this refactor is better:

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;
}

let orderFromBackEnd = this.orderFromBackEnd.bind(this);
let announcePurchase = this.announcePurchase.bind(this);

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

orderFromBackEnd(enoughQuantity:boolean) {
let finishProgress = () => this.inProgress = false;
this.inProgress = enoughQuantity;
return !enoughQuantity ? false :
this.backend.order(sku,qty).finally(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, …