Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return value instead of a promise [to stop nested deferred promise]

I've a bunch of functions which are nested due to top level function is a ajax request. So i want to return a value instead of a promise in nested child function.

Parent

let getUserPermissions = function(id) {
      let deferred = $q.defer();
      let promise = accessRequestService.getPermissions(id);
      promise.then(function(data) {
        deferred.resolve(data);
      }, function(err) {
        deferred.reject(err);
      })
      return deferred.promise;
    }

Child 1

$rootScope.userInit = function() {
        return getUserPermissions(vzid)
          .then(function(data) {

            //Some code here

            return data;
          })

    }

Child 2

let checkAuthorize = function(toState) {
  return $rootScope.userInit().then(
    function(data) {
//some code here 
      return data;
    });
}

Level 3

checkAuthorize(toState).then( function(val){ 
 $rootScope.isAuthorized = val;
  if ($rootScope.isAuthorized == true) {
        $log.info('is Authorized')
      } else {
        $log.info('is not Authorized');
        throw new AuthorizationError()
      }
  })

At Level 3 we are still working with a promise. Can child 2 return a value instead of promise.

Expectation @ Level 3

$rootScope.isAuthorized = checkAuthorize(toState);

  if ($rootScope.isAuthorized == true) {
      $log.info('is Authorized')
      } else {
      $log.info('is not Authorized');
      throw new AuthorizationError()
     }
like image 531
Sumit Ridhal Avatar asked Jun 21 '17 12:06

Sumit Ridhal


1 Answers

The hard truth is: you can't, unless you want spaghetti code all around.

The best solution would be to use something like ui-router's resolve, getting all the permissions needed before the page is shown to the user. Then, you could use them on your controllers without any asynchronous calls.

like image 86
tiagodws Avatar answered Oct 12 '22 20:10

tiagodws