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

$timeout wrapping $http.post return undefined instead of promise

本文关键字:promise undefined 返回 timeout 包装 http post      更新时间:2024-05-08

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

CCD_ 2。

之所以会发生这种情况,是因为$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
};

提前谢谢。

您得到的是TypeError: Cannot read property 'catch' of undefined,因为您根本没有从process函数返回promise。从CCD_ 8函数返回CCD_;应用.then&CCD_ 10而不是CCD_ 11承诺对象。

通过返回$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);
};