$ timeout wrap $ http.post返回undefined而不是promise

时间:2016-04-11 18:54:55

标签: javascript angularjs timeout promise angular-promise

我正在尝试提交一份要求用户电子邮件不重复的表单,但我想在POST请求之前制作一个小动画。在我得到的$scope.process函数中:

TypeError: Cannot read property 'catch' of undefined

这种情况正在发生,因为$scope.process$http.post完成之前返回,但我怎样才能使process()返回promise而不是undefined?

所以,这就是我到目前为止所做的:

//The submit form function
$scope.submitForm = function () {

  $('.btn').attr('disable');

  if ($scope.form.$valid) {

    $scope.process($scope.account)
    .catch(function (err) {

      if (err.code === 'duplicate') {
        // handle error
      }

    });

    return false;
  }
};

//This is the one in charge to send the request
$scope.process = function(body) {

  // Timeout before http post to wait for animation
  $timeout(function() {

    return $http.post(postUrl, body).then(function (response) {
      // This return a promise if I remove the $timeout
      var nextPage = response.data;
    }).catch(function (err) {
      throw err;
    });
  }, 300);

  // Return undefined due to $timeout
};

提前致谢。

1 个答案:

答案 0 :(得分:2)

您收到了TypeError: Cannot read property 'catch' of undefined,因为您根本没有从process函数返回承诺。 从$timeout函数&返回process承诺申请.then& .catch超过$timeout承诺对象。

通过返回$timeout服务,内部$http.post将返回一个数据,这样就可以建立正确的链接机制。

<强>代码

$scope.process = function(body) {
  // returned promise from here
  return $timeout(function() {
    //returned $http promise from here.
    return $http.post(postUrl, body).then(function (response) {
      // This return a promise if I remove the $timeout
      nextPage = response.data;
      return nextPage; //return data from here will return data from promise.
    }).catch(function (err) {
      throw err;
    });
  }, 300);
};