$ http promise不等待在其内部完成循环

时间:2017-12-13 16:25:41

标签: javascript angularjs

我试图在forEach请求中运行AngularJS $http循环,其中承诺不等待完成循环,在此之前它返回。

请在下面找到我的代码:

return $http({
    method: 'GET',
    url: $rootScope.baseUrl + 'test/test/test/test',
    headers: {
      "token": token
    }
  })
  .then(function(responce) {
    var dashboardCheck = function() {
      var defer = $q.defer();
      angular.forEach($rootScope.getDashboardDetails.dashboardList, function(value, key) {
        if (value.name == "Dashboard" && value.contentDashboard == true) {
          //return value;
          defer.resolve(value);
        }
      })
      return defer.promise;
    }
    var availableDashboard = function() {
      return $rootScope.getDashboardDetails.dashboardList[0];
    }
    var defaultDash = function(value) {
      method goes here
    }
    if (dashboardCheck()) {
      defaultDash(dashboardCheck());
    } else {
      defaultDash(availableDashboard())
    }
  })

1 个答案:

答案 0 :(得分:1)

你似乎让一切都变得比它应该更复杂,你想找到一个特定的仪表板,如果没有找到只返回第一个。

发出请求后没有异步代码,你没有对请求做任何事情,所以我不确定你为什么要这么做。

你想要做的更简单的版本是:

return $http({
    method: 'GET',
    url: $rootScope.baseUrl + 'test/test/test/test',
    headers: {
      "token": token
    }
  })
  .then(function(responce) {
    var scopeDashboard = $rootScope.getDashboardDetails.dashboardList;
    var dashboard = 
      //not sure why need to return a defer here, no async code provided
      scopeDashboard.filter(
        dashboard=>
          dashboard.name == "Dashboard" && dashboard.contentDashboard == true
      )[0] || scopeDashboard[0];
      // if scopeDashboard is an object try this
      // scopeDashboard[
      //   Object.keys(scopeDashboard)
      //     .filter(
      //       key=>
      //         scopeDashboard[key].name == "Dashboard" && 
      //           scopeDashboard[key].contentDashboard == true
      //     )[0] || 0
      //   ];
    return [dashboard,response];
  })
  .then(
    ([dashboard,response])=>{
      //you now have the response and dashboard, what would you like to do with it?
    }
  )
  .catch(
    err=>console.error("something went wrong",err)
  )