AngularJS $q 服务是否支持 .then(undefined) 作为空操作

Does AngularJS $q service support .then(undefined) as a no-op

当使用 AngularJS $q 服务放置条件逻辑来管理给定的延续是否应该链接在承诺链中时,如果认为能够定义或未定义某些函数会很好关于我是否希望将它们包括在内。

例如

const maybeDoThis = yesNoMaybeSo ? 
    function (data) { return data; } : 
    undefined

doSomethingReturningAPromise()
    .then(doAnotherThing)
    .then(maybeDoThis)
    .then(doYetAnotherThing)

这可以使用 $q 服务吗?我无法在 documentation 中找到详细信息并且测试它似乎太痛苦了,因为需要脚手架才能获得简单的示例设置。

如果不是,我最好只使用像下面这样的函数而不是未定义的函数吗?

function identity(value) { return value; }

简短的回答是肯定的!这个有可能。如果您添加 .then(undefined) angular 不会大惊小怪,它什么都不执行并继续执行其余语句。

我创建了一个快速 jsfiddle 作为功能证明。打开开发控制台以查看针对不同条件显示的日志信息。

https://jsfiddle.net/dougefresh/ysvfgq3j/

为了清楚起见,我也在这里粘贴了代码,但它在 fiddle 中运行良好。

var app = angular.module('myApp', []);


app.controller('ExampleCtrl', ['$scope', '$log', '$q', function($scope, $log, $q) {
  $scope.maybeDoThis = null; 
    $scope.example = function(input) {
  $scope.maybeDoThis = input ? function() { $log.info('conditional function!');} : undefined; 
    $log.info('Button pushed');
    $scope.promise(true)
      .then(function(val) {
        $log.info('first then');
      })
      .then($scope.maybeDoThis)
      .then(function(val) {
        $log.info('third then');
      })
      .catch(function(val) {
        $log.info('catch!');
      });
  };

  $scope.promise = function(answer) {
    $log.info('promise run');
    var deferred = $q.defer();
    if (answer) deferred.resolve('TRUE');
    else deferred.reject('FALSE');
    return deferred.promise;
  }
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-controller="ExampleCtrl">
  <button ng-click="example(true)">
    CLICK ME TO RUN A FUNC
  </button>
  <button ng-click="example(false)">
    CLICK ME TO RUN UNDEFINED
  </button>

</div>

是的,您可以将 undefined 或 null 传递给 .then(),它会被有效地忽略。例如,下面的代码将注销 'test':

$q.resolve('test')
    .then(undefined)
    .then(val => console.log(val));

顺便说一下,如果你曾经在 promise 上使用过 .catch(someFunction),这相当于调用 .then(null, someFunction),所以你实际上已经使用 promise 的这个特性有一段时间了:)