简体   繁体   English

如何退回虚假承诺?

[英]How to return an empty promise?

I have this code: 我有以下代码:

  var updateLogin = function updateLogin() {
     var parameters = $location.search();
     if(parameters.votoken) {
         // return a promise
         return authenticationService.updateCurrentToken(parameters);
     }

    //just logout and redirect to match another route
    authenticationService.logout()['finally'](function logoutComplete() {
        $location.url('/unauthorized');
    });
  }

    var redirectToHome = function redirectToHome() {

    $injector.invoke(updateLogin).then(() => {
           //some action here
    });
  }  


  redirectToHome();

As you can see, if the updateLogin method matches a condition it will return a promise and it works fine, but if not, the method doesnt return a promise and redirect the user to a new location, then i get this error on console Cannot read property 'then' of undefined and its obvious why. 如您所见,如果updateLogin方法符合条件,它将返回一个Promise,并且可以正常工作,但是,如果不匹配,该方法将不返回Promise并将用户重定向到新位置,那么我会在控制台上看到此错误, Cannot read property 'then' of undefined及其明显的原因。 I would like to know what is the best approach to avoid that. 我想知道避免这种情况的最佳方法是什么。 If I return the authenticationService.logout() promise, how do I know if i will need to execute this method $location.url('/unauthorized'); 如果我返回authenticationService.logout()承诺,如何知道我是否需要执行此方法$location.url('/unauthorized'); on the .then(() => snippet? .then(() =>代码段上?

Can return $q.reject() in your else . 可以在您的else返回$q.reject() Remember to also inject $q 记住也要注入$q

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM