0

I am building a function that has multiple functions running within it but I want the output to be the value of a single variable. When using coffee script there is no way for me to specify which value I want returned and so it returns multiple functions.

It is very possible that the way I'm writing the code is wrong so feel free to give suggestions.

when i do a console log of the function i get an output like this

Object {then: function, catch: function, finally: function}

The only thing I want returned is the value of ShopAverages, so I expect a number.

here is the function in coffee script

  KPIaverage = (period, KPIName, params) ->
    Sads.shops.getList(params).then (data) ->
      shops = data.map((d) ->
        new ScopeShopWithMetrics(d, $scope.organizations.current)
      )
      $q.all(shops.map((d) ->
        d.getAverages period
      )).then ->
        shopSUM = 0
        i = shops.length
        shopSUM += shops[i]["metrics"][KPIName]["value"]  while i--
        ShopAverage = shopSUM / shops.length

here is the converted JS output i get when using http://js2coffee.thomaskalka.de/

var KPIaverage;
KPIaverage = function(period, KPIName, params) {
  return Sads.shops.getList(params).then(function(data) {
    var shops;
    shops = data.map(function(d) {
      return new ScopeShopWithMetrics(d, $scope.organizations.current);
    });
    return $q.all(shops.map(function(d) {
      return d.getAverages(period);
    })).then(function() {
      var ShopAverage, i, shopSUM;
      shopSUM = 0;
      i = shops.length;
      while (i--) {
        shopSUM += shops[i]["metrics"][KPIName]["value"];
      }
      return ShopAverage = shopSUM / shops.length;
    });
  });
};

using angularjs if that makes a difference

grasshopper
  • 918
  • 4
  • 13
  • 29
  • So, this looks like yet another duplicate of http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call. You cannot return things from async code. Return the promise, and handle the response with a callback. – elclanrs Aug 24 '14 at 19:50
  • Also, you don't need that many parentheses in the latest CoffeeScript. This will compile the same in CS 1.7+ http://dpaste.com/1AJHX0Z – elclanrs Aug 24 '14 at 19:51
  • return the promise? but I need this to occur after the promise. – grasshopper Aug 24 '14 at 19:53
  • Right, so return the promise, then handle the response with a callback somewhere else. – elclanrs Aug 24 '14 at 19:57

0 Answers0