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 // since it is resolved, the handler will execute immediately newPromise.then($log.log); // 123
Tip
JSFiddle: http://jsfiddle.net/msfrisbie/ftgydnqn/
How it works…
The $q.when()
method wraps whatever is passed to it with a new promise. If it is passed...