如何从Promise函数获得响应。那么?

时间:2016-08-22 08:50:39

标签: javascript html angularjs angular-promise

我的HTML中有以下2个输入元素:

<input type="date" ng-model="calendarStart" class="form-control" style="display: inline-block; width: 180px !important;" />
<input type="date" ng-model="calendarEnd" class="form-control" style="display: inline-block; width: 180px !important;" />

并拥有.js:

$scope.calendarStart = new Date();
$scope.calendarEnd = new Date();
$scope.calendarEnd.setDate($scope.calendarEnd.getDate() + 7);

var firstEndDate = new Date();
var firstStartDate = new Date();

var startData = "calendarStart";
var endData = "calendarEnd";

$scope.changeCalendarStart = function () {           
   dataService.settings_get(startData).then(function(response) {
      firstStartDate = response;
         if (firstStartDate != null) 
            $scope.calendarStart = firstStartDate;

      return firstStartDate;
   });
   return firstStartDate;
};

如何从.then函数中获取响应值,caz需要更改输入值?

1 个答案:

答案 0 :(得分:0)

你不理解承诺和他们的链接。它们是异步的,因此您不能将值作为“firstStartDate”返回给其调用者,因为调用者不知道何时来获取它。

因此,请尝试将changeCalendarStart更改为以下内容:

$scope.changeCalendarStart = function () {           
  return $q.function(resolve, reject){
     dataService.settings_get(startData).then(function(response) {
      firstStartDate = response;
         if (firstStartDate != null) 
            $scope.calendarStart = firstStartDate;

      resolve(firstStartDate); //from here, we are going to the then function of the caller below
   });
  }
};

并将其用作承诺,例如这样:

$scope.changeCalendarStart().then(function(resultValue){ //this inner function it's called by the row with resolve(firstStartDate) above
  $scope.myResultValue = resultValue; 
}

我建议你按照承诺教程来完全理解它们。 This就是一个很好的例子。