javascript - Angular : How to make one async function executes first after another

标签 javascript angularjs

我有一个保存函数,我需要调用另一个函数来获取修订号。并且正在进行 api 调用。因为两者本质上都是异步的。如何让一个函数等待其他函数执行

$scope.getRevision = function(callback){
    Api.Product.querymyProdById({ prodId: $scope.editProdId }).$promise.then(function(result) {
        if (result && result.length>=1 && result[0].effectiveDate != $scope.editProdmyDate) {
            $scope.editProdRevision = result && result[0].revision +1;
            callback();
        } else {
            $scope.editProdRevision = 100;
        }
    });
}

$scope.saveProd = function(){
     $scope.getRevision(function(){});

     Api.Product.save({
        id: $scope.ProdId;
        revision:$scope.editProdRevision
         -some code

}

上面的代码我想确保在我得到 prodRevision 之前不会调用保存 api。

有什么建议吗?

最佳答案

既然你有 promise ,就不要搞乱回调。让您的函数实际返回一个 promise 并使用 then 来链接调用。

$scope.getRevision = function(){
    return Api.Product.querymyProdById(..).$promise...;
}

$scope.saveProd = function() {
   return $scope.getRevision().then(function() {
        return Api.Product.save(...);
   })
}

关于javascript - Angular : How to make one async function executes first after another,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37721037/

相关文章:

javascript - jQuery 每个这个

javascript - 如何使用日期对象作为线性轴的刻度标签?

javascript - 使用 ng-options 选择时的绑定(bind)问题

javascript - 清除 Angular UI Bootstrap typeahead 上的 $viewValue

javascript - 使用 Javascript 和 Angular 操作两个列表多选中的值

javascript - 如何向 Flask Server 发送数据?

javascript - 未提交 JQuery Datepicker 值

javascript - meteor 巴贝尔配置

javascript - 跨不同对象同步画笔

javascript - AngularJS:console.log 不显示任何内容