以角度创建空头承诺?

编程入门 行业动态 更新时间:2024-10-27 12:35:57
本文介绍了以角度创建空头承诺?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我想做这样的事情:

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

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

更多推荐

[db:关键词]

本文发布于:2023-04-22 04:52:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1015687.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:空头   角度

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!