本文介绍了以角度创建空头承诺?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做这样的事情:

var promise = IAmAEmptyPromise;

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

promise.then(function(){
    //do something
});

所以我想声明一个promise,可以使用then来解决.然而,这个承诺可能会被另一个承诺覆盖,它返回内容.后来我想解决这个承诺是否有内容.这可能吗?我试过:

So I want to declare a promise, which can be resolved using then. However this promise may be overwritten by another promise, which returns content. Later I want to resolve the promise whether it has content or not. Is this possible? I tried with:

var promise = $q.defer().promise;

if(!$scope.user){
    promise = UserService.create(params);
}

promise.then(function(){
   //either user was created or the user already exists.
});

但是,当用户在场时这不起作用.有什么想法吗?

However this does not work when a user is present. Any ideas?

推荐答案

就像 Bixi 写的那样,您可以使用 $q.when() 将承诺或值包装到承诺中.如果您传递给 when() 的是一个承诺,它将被返回,否则将创建一个新的承诺,该承诺直接使用您传入的值进行解析.像这样:

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.
});

这篇关于以角度创建空头承诺?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 18:35