可能重构代码以使用链式承诺
potentially refactor code to use chained promises
下面的代码工作正常,但似乎应该有更简洁的方式来编写它。我一直在寻找链式承诺的例子,但没有找到任何足够接近这个逻辑的东西来弄清楚如何从这个到链式方法的转换。可以吗?
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);
});
链接这些调用会导致它们一个接一个地执行。从您的代码的外观来看,这似乎不是必需的。你可以做的是将它们组合在一起。
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 使它看起来更干净。
使用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);
});
}
下面的代码工作正常,但似乎应该有更简洁的方式来编写它。我一直在寻找链式承诺的例子,但没有找到任何足够接近这个逻辑的东西来弄清楚如何从这个到链式方法的转换。可以吗?
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);
});
链接这些调用会导致它们一个接一个地执行。从您的代码的外观来看,这似乎不是必需的。你可以做的是将它们组合在一起。
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 使它看起来更干净。
使用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);
});
}