Search code examples
javascriptangularjsangular-promiseecmascript-5

handle a function that returns a promise or a null value


I have defined a function as following :

function getCurrentComponent(){
    if($rootRouter._currentInstruction){
        return $rootRouter.recognize($rootRouter._currentInstruction.urlPath).then(function (data) {
            return data.component.componentType;
        });
    }else{
        return null;
    }
}

To call this function I did as following :

factory.getCurrentComponent().then(function (data) {
    ...
});

The problem is when the getCurrentComponent function returns a null value, the following error is generated :

Cannot read property 'then' of null

How can I solve this ?

Edit:

I forgot to say that I'm limited to use ES5, so I can't work with the object Promise


Solution

  • I cant use the object Promise in ES5.

    Use the AngularJS $q Service:

    function getCurrentComponent(){
        if($rootRouter._currentInstruction){
            return $rootRouter.recognize($rootRouter._currentInstruction.urlPath).then(function (data) {
                return data.component.componentType;
            });
        }else{
            ̶r̶e̶t̶u̶r̶n̶ ̶n̶u̶l̶l̶;̶
            return $q.reject(null);
        }
    }
    

    AngularJS modifies the normal JavaScript flow by providing its own event processing loop. This splits the JavaScript into classical and AngularJS execution context. Only operations which are applied in the AngularJS execution context will benefit from AngularJS data-binding, exception handling, property watching, etc.

    The $q Service is a Promises/A+-compliant implementation of promises/deferred objects thst is integrated with the AngularJS framework and its digest cycle.