我正在尝试解决如何链接多个 js 函数(本例中为两个)。我有一个 JavaScript 函数用于 save(),另一个用于 saveAndPrint()。我需要链接该调用,因为我需要在 save() 中生成的 id 来转发它以便在第二个调用中进行打印。也许我只能使用一个函数来完成这两件事,但我想学习如何做到这一点。目前我只是得到一个“未定义”,因为第二个函数在第一个函数完成之前启动。 这是代码:
$scope.save = function () {
var receipt = {
documentType: 'RCI',
expirationDate: new moment().format('YYYY-MM-DD'),
person: {id: $scope.financeDocuments[0].person.id},
payments: getPayments(),
promotions: [],
creationDate: new moment().format('YYYY-MM-DD'),
compensatedDocuments: getDocumentsToPay()
};
financeDocumentService.save(receipt, function (response) {
receipt = response;
$uibModalInstance.close(response);
}).$promise.then(function (data) {
return receipt;
});
};
$scope.saveAndPrint = function() {
var document = $scope.save();
$window.location.href = "#/finance/receipt_show/"+document.id;
};
非常感谢!
最佳答案
首先返回 promise :
$scope.save = function () {
var receipt = {
documentType: 'RCI',
expirationDate: new moment().format('YYYY-MM-DD'),
person: {id: $scope.financeDocuments[0].person.id},
payments: getPayments(),
promotions: [],
creationDate: new moment().format('YYYY-MM-DD'),
compensatedDocuments: getDocumentsToPay()
};
//RETURN the promise
͟r͟e͟t͟u͟r͟n͟ financeDocumentService.save(receipt, function (response) {
receipt = response;
$uibModalInstance.close(response);
}).$promise.then(function (data) {
return receipt;
});
};
然后从 promise 中链接:
$scope.saveAndPrint = function() {
var promise = $scope.save();
promise.then(function(receipt) {
$window.location.href = "#/finance/receipt_show/"+document.id;
});
};
欲了解更多信息,
关于javascript - 如何以编程方式链接两个js函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44999018/