When working with synchronous or asynchronous functions you way wrap it into a new promise, either to make a synchronous function asynchronous or to wrap an asynchronous function into your own customized promise. To do that, we will use Angular’s $q service. This is a service that helps you run functions asynchronously, and use their return values (or exceptions) when they are done processing.

Wrap a synchronous function into a promise

The below code wraps a synchronous function into an asynchronous function.

With the above example, we are now in the position to call the async method and do something with the result when the event happens, either when it was successful or when an error occurred.

Wrap an asynchronous function into a new promise

The second code example shows, how we can wrap an already asynchronous function with promises into a new one. This is usable when you have to do something with the first response, but you have to give to the next function also some feedback. Some people would say there is no need for that, but we needed it 🙂 With the below code, I want to show how you can wrap your promise into a new one.

$scope.original method

This method is the usual way how we would call a resource or other method which returns a promise. When the promise is successful, we set the response to $scope.myIp.

$scope.deferred method

This method is pretty similar to what the original one is, but, we are packing the promise into a new promise. We are creating a deferred object with $q.defer(). When the promise is succesful, we pack it into a new successful promise with just the ip, instead of the whole object. In case of a failure, we write our own Error message.

$scope.userOfDeferred method

This method now uses the deferred method. We can then do something with the result or error. Read more about $q.defer() here: https://docs.angularjs.org/api/ng/service/$q

Wrap a function into a new promise with Angular’s $q service
Tagged on:     

Leave a Reply

Follow

Get every new post on this blog delivered to your Inbox.

Join other followers:

Welcome Damir Kusar

Log in

Lost your password?
%d bloggers like this: