如何以编程方式链接两个js函数?

时间:2017-07-09 17:16:34

标签: javascript angularjs

我正在尝试解决如何链接几个js函数(在本例中为两个)。我有一个javascript函数来保存()另一个用于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;
};

非常感谢!

1 个答案:

答案 0 :(得分:1)

首先返回承诺:

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

然后来自承诺的

$scope.saveAndPrint = function() {
    var promise = $scope.save();     
    promise.then(function(receipt) {                    
        $window.location.href = "#/finance/receipt_show/"+document.id;
    });
};

欲了解更多信息,