如何在angular js中处理多个异步post方法

How to handle multiple asynchronous post method in angular js?

本文关键字:异步 post 方法 处理 angular js      更新时间:2023-09-26
$scope.savekbentry = function (value) {
        console.log('save clicked');
        console.log(value);
        console.log($scope.kbentry.kbname);
        $scope.kbentry.mode = value;
        var kbname = $scope.kbentry.kbname;
        var kbdescription = $scope.kbentry.kbname;
        var kbmode = "";
        var type = "";
        if ($scope.kbentry.mode == 'symptom') { kbmode = 1; type = 'SYM' }
        if ($scope.kbentry.mode == 'allergy') { kbmode = 3; type = 'ALG' }
        $http.post('../AjaxRequestData.aspx/AddKBEntry', { KB_Name: kbname, KB_Des: kbdescription, KB_Mode: kbmode })
        .success(function (data, status, headers, config) {
            $scope.transport = {
                method: 'post',
                read: '../WM_Autocomplete/GetAutocompleteData.aspx/GetSingletonLst',
                params: { type: type }
            }
        })
        .error(function (data, status, headers, config) {
        });
        clear();
    }

在上面的代码中,我想在第一次发帖成功后调用另一个异步发帖方法。目前它没有按照上面的代码工作。如何通过回调函数来处理这个问题?

您可以使用then()链接并解析$http的请求承诺,例如:

var getSingletonPromise = function(type){
  return $http.post('.../GetSingletonLst', type) // returns a promise 
};
var addEntryPromise = function(params){
  return $http.post('.../AddKBEntry', params)  // returns a promise
};
$scope.savekbentry = function (value) {
  addEntryPromise().then(function(){ // use then() to resolve your promise
    // addEntry onSuccess
  }).getSingletonPromise().then(function(){
      // addEntry onSuccess
    }); 
}

你也可以考虑将$http请求分离到一个单独的工厂/服务中,并添加错误处理。
请注意,上面的代码尚未经过测试,但提供了一个可能解决方案的大纲。