等到最后一个函数完成它的工作,然后在 angularjs 中

Wait till last function finish its work then in angularjs

本文关键字:工作 然后 angularjs 最后一个 函数      更新时间:2023-09-26

我正在创建一个小应用程序,其中有 40 个小部件,我正在循环和获取数据并重新绘制它。

    $scope.loopWiget = function(){
    for(var i=0; i < $scope.totalWidget.length; i++)
    {
     if($scope.totalWidget[i].widgetType == "chart"){
     $scope.fetchData($scope.totalWidget[i]);}
    if($scope.totalWidget[i].widgetType == "table"){
     $scope.fetchDataFortable($scope.totalWidget[i]);}
    }
     };
     $scope.fetchData = function(id){
    // fetching data and in response calling other function
    $http({
       method: 'POST',
       url: 'rest/dataset/metadata',
       type: 'json',
       headers:{'id':id}
     }).success(function(response){
    $scope.drawWid(response);
      }) 
     };
$scope.fetchDataFortable= function(id){
    // fetching data and in response calling other function
    $http({
       method: 'POST',
       url: 'rest/dataset/metaTabledata',
       type: 'json',
       headers:{'id':id}
     }).success(function(response){
    $scope.drawWidTable(response);
      }) 
     };
    $scope.drawWid = function(response){
      // All draw logic comes here
    };
$scope.drawWidTable= function(response){
      // All draw logic comes here
    };
$scope.totalWidget = [{'widgetId':'1','widgetType':'table'},{'widgetId':'2','widgetType':'chart'},{'widgetId':'3','widgetType':'maps'},{'widgetId':'4','widgetType':'chart'}];
    $scope.loopWiget();

现在我的循环不会等待完成 drawWid 函数并再次调用 fetchdata,因此我在第一个小部件中获取第二个小部件的数据。 那么如何在循环中等待,直到 draw 函数完成其代码,然后为下一个小部件调用 fetchData 函数。

由于这是一个异步请求,因此随机呈现数据很常见。对此,可能的解决方案很少:

第一种方法:从响应中将数据存储在数组中,当所有数据都被获取后,只调用 draw 函数来逐个渲染小部件或在循环索引处渲染小部件。

 widgets.forEach((widget, index) => {
            return this.myService.getData(widget.entityProp)
                .then(res => {
                    this.drawWid(res, index);
                });
 });

    drawWid(res, index) {
        compute logic accroding to the index of data .
    }

第二种方法:您可以使用 $q.all() 从所有请求中获取数据,然后渲染它。

你能试试以下代码吗:

var index = 0;
$scope.loopWiget = function(){
    if(!$scope.totalWidget[index]){
        return;
    }
  var id = $scope.totalWidget[index]['widgetId'];
  if($scope.totalWidget[index].widgetType == "chart"){
        $scope.fetchData(id);
      }
      if($scope.totalWidget[index].widgetType == "table"){
         $scope.fetchDataFortable(id);
      }
 };
$scope.fetchData = function(id){
     $http({
           method: 'POST',
           url: 'rest/dataset/metadata',
           type: 'json',
           headers:{'id':id}
        }).success(function(response){
                $scope.drawWid(response);
                index++;
        });
}
$scope.drawWid = function(response){
  // All draw logic comes here
  $scope.loopWiget();
};
$scope.totalWidget = [{'widgetId':'1','widgetType':'table'},{'widgetId':'2','widgetType':'chart'},{'widgetId':'3','widgetType':'maps'},{'widgetId':'4','widgetType':'chart'}];
$scope.loopWiget();
相关文章: