2016-11-13 90 views
-1

我有兩個javscript async $ http函數:我正在使用角度js以嵌套方式動態創建表。

我想要某種方式來同步執行這些功能。

現在,j循環只對resultB的初始值執行。一旦表被編譯,然後fuctB被執行爲i的所有值。

$scope.funcA = function() { 
    $http({ 
    method : 'GET', 
    url : url,     
    }).then(function successCallback(response) { 
    $scope.resultA = response.data; 
    //process based on $scope.resultA 
    for (var i = 0; i < $scope.resultA .length; i++){ 
     $scope.funcB($scope.resultA[i][0]); 
     for(j=0; j<$scope.resultB .length; j++){ 
     //process based on $scope.resultB 
     }      
    } 
    $compile(/* document element*/); 

    }, function errorCallback(response) { 
    console.log(response.statusText); 
    }); 
} 

$scope.funcB = function(k){ 
    $http({ 
    method : 'GET', 
    url : url+k 
    data: k , 
    }).then(function successCallback(response) { 
    return $scope.resultB = response.data; 
    }, function errorCallback(response) { 
    console.log(response.statusText); 
    }); 
} 
+1

更新與完整的代碼。不能診斷你正在嘗試做什麼.. – Aravind

+0

更新了問題 – rtk

+0

已清理的代碼使其更具可讀性。您已經定義了此代碼的異步預期操作。你能否以同樣的方式定義同步(細節有幫助)? – rfornal

回答

0
$scope.funcB = function(i) { 
    // return promise 
    return $http({.... 
     data: i ; 
     $scope.resultB = response.data; 
    }; 
} 


$http{..... 
$scope.resultA =response.data; 
for(var i =0; i< $scope.resultA.length; i++{ 
    process based on i value 
    $scope.funcB(i).then(function() { 
    // execute this part after promise completed (request B has ended and returned result) 
    for(var j =0; j<$scope.resultB.length;j++{ 
     process based on i and j; 
     } 
    } 
    compile(the document element); 
}); 
} 

請檢查承諾一些教程它會幫助你瞭解這是怎麼回事就在這裏,如http://liamkaufman.com/blog/2013/09/09/using-angularjs-promises/但在互聯網上有很多這些...

+0

其仍然異步工作 – rtk

+0

如果您*真的*想要進行同步呼叫檢查此:http://stackoverflow.com/questions/13088153/how-to-http-synchronous-call-with-angularjs。但是,在使用angularjs時,您希望使用承諾並進行異步ajax調用。 – csharpfolk