创建角一句空话? [英] Create empty promise in angular?

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

问题描述

我会向这样的:

var promise = IAmAEmptyPromise;

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

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

所以,我想声明的承诺,可以使用,然后加以解决。然而这个承诺也可能被其他的承诺,它返回的内容被覆盖。后来我想解决的承诺是否有内容或没有。这可能吗?我试着用:

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

然而,当用户为present这不起作用。任何想法?

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

推荐答案

碧溪一样写,你可以使用 $ q.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.
});

这篇关于创建角一句空话?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆