Reputation: 205
I am new to coffeescript and I have a coffee script code as
getProviderListDisplayValues:(domainId) ->
displayValues = []
$.ajax
contentType: 'application/json',
url: "/Services/ListProviders?domainid=#{domainId}",
success: (data) ->
for oneResponse in data
displayValues.push oneResponse.name
displayValues
which is compiled to
CounselorHome.prototype.getProviderListValues = function(domainId) {
var values;
values = [];
$.ajax({
contentType: 'application/json',
url: "/Services/ListProviders?domainid=" + domainId,
success: function(data) {
var oneResponse, _i, _len, _results;
_results = [];
for (_i = 0, _len = data.length; _i < _len; _i++) {
oneResponse = data[_i];
_results.push(values.push(oneResponse.id));
}
return _results;
}
});
return values;
};
I just want to push values to values[]
& displayValues[]
but why is the _results[]
array created? Does it hampers the browser efficiency? Is there any way removing such unnessary code? May be, by editing my coffee script.
EDIT : WORKING CONDITION
But when I put an alerting code as
$.ajax
contentType: 'application/json',
url: "/Services/ListProviders?domainid=#{domainId}",
success: (data) ->
for oneResponse in data
displayValues.push oneResponse.name
alert displayValues
displayValues
This code works and I can retrieve the required data.
Upvotes: 0
Views: 40
Reputation: 664297
Apart from that your code wouldn't work anyway, the _results
are generated because of coffeescripts implicit function return values - and loops are only expressions as well that generate arrays. The docs state:
Sometimes functions end with loops that are intended to run only for their side-effects. Be careful that you're not accidentally returning the results of the comprehension in these cases, by adding a meaningful return value — like
true
— ornull
, to the bottom of your function.
So the javascript that you expected can be created by writing
…
success: (data) ->
for oneResponse in data
displayValues.push oneResponse.name
return
…
("Trailing return
and return undefined
are now optimized away." - since version 1.0.1);
See also Is there any way to not return something using CoffeeScript?
However, what you actually want is this:
getProviderListDisplayValues:(domainId) ->
$.ajax
contentType: 'application/json',
url: "/Services/ListProviders?domainid=#{domainId}"
.then (data) ->
for oneResponse in data
oneResponse.name
…
getProviderListDisplayValues(…).then (displayValues) ->
…
Upvotes: 2