2016-06-09 38 views
1

我有一个保存函数,我需要调用另一个函数来获取修订版本号。并在那里进行API调用。因为两者本质上都是异步的。如何使一个功能,使等到其他执行Angular:如何使一个异步函数先后执行

$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 

} 

上面的代码我想确保保存API不应该叫,直到我得到的prodRevision。

有什么建议吗?

+1

回报承诺,并把它们连。如果你在一个答复中返回一个承诺,那么在继续之前它会等待它解决。 – ste2425

回答

5

既然你承诺不要惹回调。让你的功能实际上返回一个承诺,并使用then来链接呼叫。

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

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

同意,Api.Product.querymyProdById应该返回一个承诺,如果您使用的是$ http,那么您可以直接返回该承诺或使用$ q创建自定义承诺。 – Markus

1

这正是JavaScript的神发明了回调

$scope.saveProd = function(){ 
    $scope.getRevision(function(){ 
     // this happens after getRevision finished 
     Api.Product.save({ 
      id: $scope.ProdId; 
      revision:$scope.editProdRevision 
      -saome code 
     }); 
    }); 

} 
0

你可以简单的化妆一个异步调用前一后,像这样的 -

// First Simple GET request example: 
$http({ 
    method: 'GET', 
    url: '/someUrl' 
}) 
.then(function successCallback(response) { 
    // this callback will be called asynchronously 
    // when the response is available 
    // Second Simple GET request example: 
    $http({ 
    method: 'GET', 
    url: '/someUrl' 
    }) 
    .then(function successCallback(response) { 

    }, function errorCallback(response) { 

    }); 
}, function errorCallback(response) { 
    // called asynchronously if an error occurs 
    // or server returns response with an error status. 
}); 
+2

如果你返回第二个'$ http',它会平滑链条。意味着您可以在更高级别注册第二个'.then',这将等待两个AJAX请求完成。不应该将承诺视为嵌套回调。 – ste2425

+0

@ ste2425你可以请一个例子请解释一下,或者我可以读一些资源的链接?谢谢! – atefth

+1

继承人[pastebin](http://pastebin.com/9PMf9TZn)你的例子。和[博客文章](http://solutionoptimist.com/2013/12/27/javascript-promise-chains-2/)可能有所帮助。承诺是出色的东西,但是与回调相比,它是一个完整的工作方式。你可以得到真正简洁的数据流。你可以像你一样嵌套它们(对于复杂链条很有用),但是这个用例并没有要求它。展平链条将具有完全相同的效果并且更具可读性。 – ste2425

相关问题