是否可以从 AngularJS 中 $http.get 的成功方法中返回一个值?

Hen*_*y C 3 javascript asynchronous promise angularjs angular-promise

此刻,我对承诺有点头脑风暴。

鉴于以下代码:

$scope.getData = function(user) {

    return $http.post('/endpoint', "some post data", { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } })
        .success(function (response) {

            var myThing = { stuff: response.infoData };

            localStorageService.set('myData', { stuff: response.infoData });

            return myThing;
    });
};
Run Code Online (Sandbox Code Playgroud)

是从成功回调返回的myThing对象:

  • 作为 $scope.getData 方法的结果返回,或
  • 被忽视和迷失在哪里?

据我了解:

  • 因为 $http.post 是一个promise,所以异步解析然后运行success方法
  • 当成功方法运行时,它返回 myThing 对象,但这并不会神奇地替换整个 $http.post 承诺本身

这样对吗?是否有我遗漏的东西,在成功方法中返回对象有什么好处,还是返回是多余的?(我很清楚这是可以改进的代码,但我试图具体找出为什么有人会写这个,或者这完全是一个错误)

Pan*_*kar 5

使用success/error回调$http方法不会使您能够从中返回数据。承诺确实提供了这种能力。它目前的写作方式会做它看起来的事情。LikemyThing不会通过当前实现返回(那里是多余的 return 语句)。

为什么有人会写这个,或者如果这完全是一个错误?

实现此方法的人试图从中返回数据,但我不认为他通过查看当前代码而成功。

利用$http方法返回的承诺,这将使您能够通过异步调用形成承诺链。为此,您需要使用.then代替.success方法。

$scope.getData = function(user) {
    return $http.post('/endpoint', "some post data", { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } })
      .then(function (res) {
          var response = res.data;
          var myThing = { stuff: response.infoData };
          localStorageService.set('myData', { stuff: response.infoData });
          return myThing;
    });
};
Run Code Online (Sandbox Code Playgroud)

如果您真的有兴趣通过调用getData方法检索数据,那么您可以使用getData方法,您应该将.then函数放在它返回的承诺上以链接它。

$scope.getData().then(function(thing){
    console.log(thing);
})
Run Code Online (Sandbox Code Playgroud)

旁注 .success方法上的error功能$http已弃用