knot22
knot22

Reputation: 2768

potentially refactor code to use chained promises

The following code works fine but it seems like there should be a more concise way to write it. I have looked for examples of chained promises but haven't found anything close enough to this logic to figure out how to do the conversion from this to the chained approach. Can it be done?

var vm = this;

accountingAppService.getInvoiceTypes().then(function (result) {
    vm.invoiceTypes = result;
}, function (e) {
    onError(e);
});

accountingAppService.getReceivablesTypes().then(function (result) {
    vm.receivablesTypes = result;
}, function (e) {
    onError(e);
});

accountingAppService.getGeneralLedgerAccounts().then(function (result) {
    vm.generalLedgerAccounts = result;
}, function (e) {
    onError(e);
});

Upvotes: 0

Views: 39

Answers (2)

georgeawg
georgeawg

Reputation: 48968

Use array.forEach and property accessors:

var getList = ["invoiceTypes","receivableTypes","generalLedgerAccounts"];

getList.forEach(x => getGeneric(x));

function getGeneric(name) {
    var capName = name[0].toUpperCase() + name.slice(1);
    var getFn = accountingAppService["get"+capName];
    getFn().then(function(result) {
        vm[name] = result;
    }, function (e) {
        onError(e);
    });
} 

Upvotes: 2

yBrodsky
yBrodsky

Reputation: 5041

Chaining those calls would cause them to execute on after the other. And from the looks of your code, that doesnt seem to be neccesary. What you can do is group them together.

Promise.all([
  accountingAppService.getInvoiceTypes(),
  accountingAppService.getReceivablesTypes(),
  accountingAppService.getGeneralLedgerAccounts()
]).then(function (results) {
 vm.invoiceTypes = results[0];
 vm.receivablesTypes = results[1];
 vm.generalLedgerAccounts [2];
}).catch(onError);

Seems like you get rid of some code. You could even use destructuring and async/await to make it look even cleaner.

Upvotes: 2

Related Questions