Reputation: 6901
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;
});
}
Upvotes: 6
Views: 2546
Reputation: 18740
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();
Upvotes: 1
Reputation: 276306
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.
Upvotes: 7