Attempting to retrieve the result of a variable after completing all asynchronous processes in a function. I've discovered that I need to use promises for this, so I spent today learning about them.
I've implemented promises in my function and consulted various tutorials, but I keep encountering an error. It seems like there might be an issue with how I'm handling kpiDefault or the implementation of my kpiAverage function. Additionally, using coffee script could potentially introduce syntax errors.
Below is my code snippet for kpiAverage:
kpiAverage = (period, kpiName, params) ->
result = $q.defer()
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
).then((shopAverage) ->
result.resolve(shopAverage)
result.promise
)
Now let's take a look at the problematic code:
kpiDefault = kpiAverage(period7, "visits", testParams).then((shopAverage) ->
shopAverage
)
When I execute this code, although it doesn't throw an error, the output isn't a number; instead, it appears to be a promise object.
kpiDefault = kpiAverage(period7, "visits", testParams)
Output:
Object {then: function, catch: function, finally: function}
Edit:
It seems I've been misusing promises all along, leading to further confusion. My goal is simply to return the value after finishing the asynchronous process, yet I'm more puzzled than before.
Upon reviewing the code, I identified and resolved the cause of the error (an old uncommented code), yet I'm still receiving a promise object as output.