2

这是我发现的最相关的事情:https ://stackoverflow.com/a/11972028/110233

当我只想返回一个东西时,它似乎工作正常,但是当其他东西取决于第一件事时,我不确定如何返回多个东西。

因为这有点迟钝,所以这是我目前正在做的一个小例子:

window.EventRosterCtrl = ($scope, subevent) ->
    $scope.subevent = subevent

EventRosterCtrl.resolve = 
    subevent: (SubEvent, $route) ->
        deferred = $q.defer()

        SubEvent.get {subevent_id: $route.current.pathParams.subevent_id}, (subevent) ->
            deferred.resolve subevent

        return deferred.promise

这是我想做的一个例子:

window.EventRosterCtrl = ($scope, subevent, addresses) ->
    $scope.subevent = subevent
    $scope.addresses = addresses

EventRosterCtrl.resolve = 
    subevent: (SubEvent, $route) ->
        deferred = $q.defer()

        SubEvent.get {subevent_id: $route.current.pathParams.subevent_id}, (subevent) ->
            deferred.resolve subevent

        return deferred.promise

    addresses: (User) ->
        deferred = $q.defer()

        # how do you get subevent called first and how would you access it here?
        for participant in subevent.participants
            User.get {user_id: participant.user}, (user) ->
                addresses[participant._id] = user.address

        deferred.resolve addresses

        return deferred.promise
4

3 回答 3

4

您需要使用 .then() 链接承诺

  var promise = firstOperation();
  承诺 = promise.then(函数(值){
    // 做更多的工作
    返回值;// 它可以是另一个promise
  });
  回报承诺;// 当两个步骤都解决时,这一个将被解决
于 2012-09-07T05:47:50.183 回答
2

好的,所以您无法以这种方式控制它,但想到的解决方法(当一个解决方案首先取决于另一个完成时)只需将所有内容放在一个对象中并解决它。最终对我最有效的是提供服务,但要遵循我原来的例子:

window.EventRosterCtrl = ($scope, info) ->
    $scope.subevent = info.subevent
    $scope.addresses = info.addresses

EventRosterCtrl.resolve = 
    info: (SubEvent, User, $route, $q) ->
        deferred = $q.defer()
        resolvedInfo = {}

        SubEvent.get {subevent_id: $route.current.pathParams.subevent_id}, (subevent) ->
            resolvedInfo.subevent = subevent

            for participant in subevent.participants
                User.get {user_id: participant.user}, (user) ->
                    addresses[participant._id] = user.address

                    if addresses.length is subevent.participants.length
                        resolvedInfo.addresses = addresses
                        deferred.resolve resolvedInfo

        return deferred.promise
于 2012-11-15T23:38:00.737 回答
-1

EventRosterCtrl 仅在子事件准备就绪时才被初始化,因此以下应该可以工作:

window.EventRosterCtrl = ($scope, subevent) ->
    $scope.subevent = subevent

    for participant in subevent.participants
        User.get {user_id: participant.user}, (user) ->
            $scope.addresses[participant._id] = user.address

EventRosterCtrl.resolve = 
    subevent: (SubEvent, $route) ->
        deferred = $q.defer()

        SubEvent.get {subevent_id: $route.current.pathParams.subevent_id}, (subevent) ->
            deferred.resolve subevent

        return deferred.promise
于 2012-09-10T18:35:09.860 回答