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

时间:2017-09-11 15:24:44

标签: javascript angularjs angular-promise

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

离。

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

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

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

如果不是我最好只使用像下面这样的身份而不是未定义的身份?

function identity(value) { return value; }

2 个答案:

答案 0 :(得分:1)

简短的回答是!这个有可能。如果添加一个.then(undefined)角度并不大惊小怪,它就不执行任何操作并继续执行其余的语句。

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

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

为了清晰起见,我还在这里粘贴了代码,但它在小提琴中运行良好。

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>

答案 1 :(得分:1)

是的,你可以将undefined或null传递给.then(),它实际上会被忽略。例如,以下代码将注销&#39; test&#39;:

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

顺便说一句,如果你曾经使用过.catch(someFunction)承诺,这就是调用.then(null, someFunction)的等价物,所以你实际上一直在使用这个承诺的功能一段时间:))

相关问题