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

标签 javascript angularjs

我正在尝试解决如何链接多个 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/

相关文章:

javascript - 是否可以减少 Google Chrome 为我的网页分配的内存?

javascript - 数组javascript中具有parentID的所有子元素的计数

javascript - 重新启动 Gif 动画

javascript - AngularJS ui-router 中的命名状态

angularjs - Angular - 如何避免在更改搜索时添加历史记录?

javascript - 处理整个 For 循环后发出嵌套 HTML5 Web SQL 查询

javascript - 如何防止ajax中给出的 header 值的可见性以进行身份​​验证

javascript - 如何将项目拖放到外部容器?

angularjs - 当 typeahead-editable 为 false 时设置输入无效

javascript - 如何使 html <p> 标签不添加换行符而是在 css 中添加尾随空格?