Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would you execute $q.when() without passing it a promise/value?

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;
});
}
like image 383
Bryce Johnson Avatar asked Sep 03 '14 15:09

Bryce Johnson


1 Answers

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.

like image 90
Benjamin Gruenbaum Avatar answered Oct 26 '22 22:10

Benjamin Gruenbaum