Creating promise wrappers with $q.when()

AngularJS includes the $q.when() method that allows you to normalize JavaScript objects into promise objects.

How to do it…

The $q.when() method accepts promise and non-promise objects, as follows:

var deferred = $q.defer()
  , promise = deferred.promise;

$q.when(123);
$q.when(promise);
// both create new promise objects

If $q.when() is passed a non-promise object, it is effectively the same as creating an immediately resolved promise object, as shown here:

var newPromise = $q.when(123); // promise will wait for a $digest cycle to update $$state.status, // this forces it to update for inspection $scope.$apply(); // inspecting the status reveals it has already resolved $log.log(newPromise.$$state.status); // 1 ...

Get AngularJS Web Application Development Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.