4

I use a method that expects a promise. Sometimes however, the promise is resolved instantly. Currently, if the promise is resolved right away, I still pass the promise, and use the following:

function instantAction()
{
    var defer = $q.defer();

    // Actions that are performed instantly

    defer.resolve();

    return defer.promise;
}

If there a way, to just return the resolve directly, such as something along the lines of return $q.resolve() and skip those two extra lines?

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Kousha
  • 32,871
  • 51
  • 172
  • 296
  • 1
    `return $q.when();` should work, but is far less intuitive and comprehensible. – Blackhole Jul 28 '14 at 00:21
  • Instantly means you have in memory data the you need to return with promise instead of going back to the server? – Ammar Khan Jul 28 '14 at 00:44
  • What do you mean by return the resolve directly? Here in this case it is resolved right away, Or did you mean you don't want to make the `instantAction` method implementation non-async in some cases? – PSL Jul 28 '14 at 01:22
  • 2
    `return $q.when();` (but unlike Blackhole I find it far more intuitive and comprehensible). – gkalpak Jul 28 '14 at 01:47
  • @ExpertSystem Actually, it's strange to use a method whose name is `when()` for such a thing. But it's not really difficult to override the `$q` service to add a `resolve()` method, directly linked to `when()`, I agree! – Blackhole Jul 28 '14 at 13:15

1 Answers1

4

As @Blackhole and @ExpertSystem said above,

$q.when(<Data or 3rd-party Promise>) will return a promise.

It's intended to make an Angular promise out of data or a 3rd party promise.

See the docs here

Michael Cole
  • 15,473
  • 7
  • 79
  • 96
  • 1
    This is a great solution for returning a dummy promise in one line. I used it for conditionally bypassing an unexposed `$http` service. – steampowered Aug 06 '15 at 23:20