AngularJS Wrap simple value into a promise using $q.when()


Example

If all you need is to wrap the value into a promise, you don't need to use the long syntax like here:

//OVERLY VERBOSE
var defer;
defer = $q.defer();
defer.resolve(['one', 'two']);
return defer.promise;

In this case you can just write:

//BETTER
return $q.when(['one', 'two']);

$q.when and its alias $q.resolve

Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted.

— AngularJS $q Service API Reference - $q.when


With the release of AngularJS v1.4.1

You can also use an ES6-consistent alias resolve

//ABSOLUTELY THE SAME AS when
return $q.resolve(['one', 'two'])