javascript - Why would you execute $q.when() without passing it a promisevalue? - Stack Overflow

According to the Angular docs on $q, $q.when() expects a promisevalue to passed in.But I just came acr

According to the Angular docs on $q, $q.when() expects a promise/value to passed in.

But I just came across someone else's code where it's called without passing in any params. Here's a simplified version of what I see:

var modal = false;

if (modalOpen) {
    return $q.when()
}
modalOpen = true;

modal = newModal({
    template: opts.template,
});

modal.result.finally(function(){ 
    modalOpen = false;
});
}

According to the Angular docs on $q, $q.when() expects a promise/value to passed in.

But I just came across someone else's code where it's called without passing in any params. Here's a simplified version of what I see:

var modal = false;

if (modalOpen) {
    return $q.when()
}
modalOpen = true;

modal = newModal({
    template: opts.template,
});

modal.result.finally(function(){ 
    modalOpen = false;
});
}
Share Improve this question edited Sep 3, 2014 at 15:40 Benjamin Gruenbaum 277k89 gold badges520 silver badges517 bronze badges asked Sep 3, 2014 at 15:34 Bryce JohnsonBryce Johnson 6,9317 gold badges46 silver badges52 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

Methods should either return synchronously or return asynchronously to remain consistent. If a method returns synchronously sometimes and still wants to keep the fact sometimes it is already resolved transparent - it returns an empty resolved promise. Having APIs that sometimes return promises and sometimes synchronously is a recipe for trouble.

Using $q.when is the simplest way to get an empty resolved promise in Angular.

If you're wondering what $q.when() returns - it returns undefined.

If you need it to return null, then do $q.when(null).

This is useful when you have a type system like TypeScript and need to know what the return type is for your method when you're unable to resolve the promise with the type requested.

const getUser = async (id: number): Promise<User | undefined> =>
    someCondition ? Api.getUser(id) : $q.when();

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744359491a4570399.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信