潜在地重构代码以使用链接的承诺

时间:2018-09-07 20:44:45

标签: angularjs angular-promise

以下代码可以正常工作,但似乎应该有一种更简洁的编写方式。我一直在寻找链式承诺的示例,但还没有找到足够接近此逻辑的东西来弄清楚如何进行从此方法到链式方法的转换。能做到吗?

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

2 个答案:

答案 0 :(得分:2)

束缚这些调用将导致它们在另一个之后执行。从代码的外观来看,这似乎不是必需的。您可以将它们分组在一起。

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

似乎您摆脱了一些代码。您甚至可以使用解构和async / await使它看起来更干净。

答案 1 :(得分:2)

使用array.forEachproperty 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);
    });
} 
相关问题