Skip to content Skip to sidebar Skip to footer

Can This Promise Nesting Be Changed To Chaining?

This is the pseudo scenario | then (items) | then (items, actions) getItems() | getActions(for:items) | apply(actions -> items) :promise | :promise

Solution 1:

Unless I'm missing something, this should be fairly straightforward, no?

(I have simplified some of your internal function signatures for clarity)

itemsResource.getItems(userId)
  .then(function(items) {
    return $q.all({
      items: items,
      actions: actionResource.getActions(items)
    });
  })
  .then(function(data) {
    applyActions(data.items, data.actions);
    $scope.model.items = data.items;
    returndata.items;
  });

plunker for illustration

Solution 2:

How about wrapping the results of the items->actions chain in a promise? Something like

return$q(function(resolve, reject) {

    var outerItems;

    itemsResource.getItems(userId).$promise
        .then(getActions)
        .then(function (actions) {
            resolve([outerItems, actions]);
        })
        .catch(function (err) { reject(err); });

    functiongetActions(items) {
        outerItems = items;
        return actionsResource.getActions(items).$promise
    }

}).then(function (itemAndActions) {
    var items = itemsAndActions[0], 
        actions = itemsAndActions[1];

    return helper.spread(function (items, actions) {
        applyActions(items, actions);
        $scope.model.items = items;
        return items;
    })
});

Post a Comment for "Can This Promise Nesting Be Changed To Chaining?"