简体   繁体   English

在“然后”声明中解决承诺

[英]Resolving a promise in a 'then' statement

With AngularJS, I resolve my promises directly in the service just like this: 使用AngularJS,我可以像这样直接在服务中兑现我的承诺:

.factory('movieService', function($http, $log, $q) {
  return {
   getMovie: function(movie) {
     var deferred = $q.defer();
     $http.get('/api/v1/movies/' + movie)
       .success(function(data) { 
          deferred.resolve({
             title: data.title,
             cost: data.price});
       }).error(function(msg, code) {
          deferred.reject(msg);
          $log.error(msg, code);
       });
     return deferred.promise;
   }
  }
 });

As stated in the documentation ( https://docs.angularjs.org/api/ng/service/ $http#) : 如文档中所述( https://docs.angularjs.org/api/ng/service/ $ http#):

The $http legacy promise methods success and error have been deprecated. $ http旧式的Promise方法成功和错误已被弃用。 Use the standard then method instead. 请改用标准然后方法。 If $httpProvider.useLegacyPromiseExtensions is set to false then these methods will throw $http/legacy error. 如果$ httpProvider.useLegacyPromiseExtensions设置为false,则这些方法将引发$ http / legacy错误。

So success and error got deprecated. 因此,不赞成successerror

How can I resolve a promise in a then statement ? 我如何在then语句中兑现承诺?

Regards. 问候。

Your code can be rewritten as: 您的代码可以重写为:

.factory('movieService', function($http, $log, $q) {
    return {
        getMovie: function(movie) {
            var deferred = $q.defer();

            $http.get('/api/v1/movies/' + movie).then(function(response){
              var data = response.data;

              deferred.resolve({
                  title: data.title,
                  cost: data.price
              });
            }, function(msg, code) {
                deferred.reject(msg);
                $log.error(msg, code);
            });

            return deferred.promise;
        }
    };
});

Although you're doing a bit more work than necessary. 尽管您要做的工作比必要的多。 It can be shortened down to: 它可以缩短为:

.factory('movieService', function($http, $log, $q) {
    return {
        getMovie: function(movie) {
            return $http.get('/api/v1/movies/' + movie).then(function(response){
              var data = response.data;

              return {
                  title: data.title,
                  cost: data.price
              };
            }, function(msg, code) {
                $log.error(msg, code);
            });
        }
    };
});

Just pass two functions to then() as parameters, the first being for success, and the second being for failure. 只需将两个函数作为参数传递给then() ,第一个用于成功,第二个用于失败。

...

$http.get('/api/v1/movies/' + movie)
.then(function(result) { 
          //Your success code here
       },
      function(result) {
          //Your fail code here
       });
...

Strictly speaking, though, then() returns a promise. 但是严格来说, then()返回一个promise。 What you're doing is waiting for it to resolve, then using that resolve to resolve another promise with the same data. 您正在做的是等待其解决,然后使用该解决方案来解决另一个具有相同数据的承诺。 You don't need to bother; 您无需打扰; just return the $http chain. 只需返回$http链。 Admittedly, they could be a little clearer about then() in the documentation for $http and $q . 诚然,在$ http$ q的文档中,它们可能对then()更为清晰。

 .factory('movieService', function ($http, $log, $q) { return { getMovie: function (movie) { var deferred = $q.defer(); $http.get('/api/v1/movies/' + movie).then( //Success as first parameter function (data) { deferred.resolve({ title: data.title, cost: data.price }); }, // Error as second parameter function (msg, code) { deferred.reject(msg); $log.error(msg, code); } ); return deferred.promise; } } }); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM