Create empty promise in angular?

后端 未结 2 2013
执笔经年
执笔经年 2020-12-09 07:31

I want to do something like this:

var promise = IAmAEmptyPromise;

if(condition){
    promise = ApiService.getRealPromise();
}

promise.then(function(){
             


        
2条回答
  •  囚心锁ツ
    2020-12-09 07:51

    Like Bixi wrote, you could use $q.when() which wraps a promise or a value into a promise. If what you pass to when() is a promise, that will get returned, otherwise a new promise is created which is resolved directly with the value you passed in. Something like this:

    var promise;
    if(!$scope.user){
      promise = UserService.create(params);
    } else {
      promise = $q.when($scope.user);
    }
    
    promise.then(function(user){
      //either user was created or the user already exists.
    });
    

提交回复
热议问题