2017-09-11 3 views
1

AngularJS $ q 서비스를 사용하여 약속 연속성 내에서 주어진 연속을 체인으로 묶어야 하는지를 결정하는 조건부 논리를 적용 할 때 훌륭하다고 생각하면 내가 포함 시킬지 여부에 따라 정의되거나 정의되지 않은 일부 기능을 가질 수 있습니다.

ex.

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

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

$ q 서비스를 사용하면 가능합니까? documentation 내에서 세부 정보를 찾을 수 없었으며 간단한 테스트 설정을 얻는 데 필요한 스캐 폴딩 때문에 너무 많은 고통이있는 것 같았습니다.

내가 정의되지 않은 대신 다음과 같은 기능을 사용하는 것이 가장 좋습니다.

function identity(value) { return value; } 
+0

예, Angular는 Promises/A + 표준을 구현합니다. – Bergi

답변

1

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>
예, 당신은 .then()에 정의되지 않았거나 널 (null) 중 하나를 전달할 수 있고, 효과적으로 무시됩니다. 예를 들어, 다음 코드는 '시험'로그 아웃됩니다 : 당신이 이제까지 약속에 .catch(someFunction) 사용했다면, 그건 그렇고

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

를 실제로 사용하고 한, 그래서이 .then(null, someFunction)를 호출 equivilent이며, 얼마 동안이 약속의 특징 :)

+0

"호출의 평등성 .then (null, someFunction)'" 아, 예, 잊어 버렸습니다. 이중 null 매개 변수가 잘 작동한다는 것은 기쁩니다. – jpierson

1

짧은 대답은 YES입니다! 이것은 가능하다. .then(undefined) 각도를 추가하면 혼란스럽지 않고 단지 아무 것도 실행하지 않고 나머지 명령문을 계속 사용합니다.

빠른 jsfiddle을 기능의 증거로 만들었습니다. dev 콘솔을 열면 다른 조건에 대해 표시되는 로그 정보를 볼 수 있습니다.

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

나 또한 여기에 명확성을 위해 코드를 붙여하지만 바이올린에 잘 실행됩니다.