currently, it's the callback that's returning the resource, which doesn't help you much. You can't delay a return statement until an async function has completed, but you can work with $q promise.
ngular.module('app').factory('newService', function($resource, configService, $q) {
var resourcePromise = $q.defer();
configService.get(function(config) {
resourcePromise.resolve($resource(config.webServicePath + '/api/names', {},
{ 'update': { method:'PUT' } }
));
});
return resourcePromise.promise;
});
Here's how $q works
- You need to return a value that you get in the future, so you defer it using
$q.defer() - This returns a deferred object.
- You make your async call, and in its success callback, you call
.resolveon the deferred object. - If the callback fails, you call
.rejecton the deferred object. - You return
deferredobject.promise, which is a promise object.
Using a service that returns promises
When you expect a value from a promise, you can listen for it by passing a callback to its thenmethod. If the promise might be rejected (the operation failed), it's a good idea to pass a second callback, which will be called when the promise is rejected.
Here's a simple example of a service that returns a promise, and how to use it: