I'd like to be able to build a User service that depends on a utility library (that contains a logger and lodash). The code I have seems very close:
angular.module("NS.services").service "utilService", ($window, $q) ->
console.log 'loading util service'
util = ->
deferred = $q.defer()
require(["cdn-lodash"], (lodash) =>
console.log 'deferred resolve'
# I plan on using a more complex logger down the road, so it'd probably be
# in another require
deferred.resolve(lib: lodash, logger: $window.logger if $window.logger?)
)
deferred.promise
util: util
angular.module("NS.services").service "userService", ['$http','utilService',
($http, util) ->
@get = (id, onError, onSuccess) ->
throw 'no id supplied' unless id?
util.logger.debug 'getting user for id' + id
$http.get("/api/user/#{id}")
.success (users) ->
util.logger.debug 'loaded users'
onSuccess(users)
.error onError
]
The problem is that the the userService
doesn't wait for the Promise to resolve before it fires off the get
method -- things aren't happening in the order that I want. I thought about wrapping the @get
method in a require, but that seems clunky and a poor case of reuse.
How can I get userService
to wait for utilService
to finish its promise before building itself?
If you userService wants to "wait" on the promise, it should call the "then" method of the promise. It does not look like that is currently happening.