How to avoid this return in nested coffeescript?

Here is what I want to see:

kango.invokeAsync('kango.storage.getItem', 'item1', function(returned1) { kango.invokeAsync('kango.storage.getItem', 'item2', function(returned2) { alert(returned1 + returned2); }); }); 

Here is what I wrote in coffeescript:

 kango.invokeAsync 'kango.storage.getItem', 'item1', (returned1) -> kango.invokeAsync 'kango.storage.getItem', 'item2', (returned2) -> alert returned1 + returned2 

The problem here is that no matter what coffeescript does the function () -> return something. In this case, the last statement is returned for some reason.

If I were to place a second warning in a nested function with a return of 2, it would return instead of the first:

 kango.invokeAsync('kango.storage.getItem', 'item1', function(returned1) { kango.invokeAsync('kango.storage.getItem', 'item2', function(returned2) { alert(returned1 + returned2); return alert('something'); }); 

How to avoid returning it?

+4
source share
2 answers

If you do not want the function to return something, just say return :

 kango.invokeAsync 'kango.storage.getItem', 'item1', (returned1) -> kango.invokeAsync 'kango.storage.getItem', 'item2', (returned2) -> alert returned1 + returned2 return 

return behaves the same in CoffeeScript as it does in JavaScript, so you can say return if you do not want any particular return value.

If you do not specify an explicit return value using return , the CoffeeScript function will return the value of the last expression so that your CoffeeScript is equivalent:

 kango.invokeAsync 'kango.storage.getItem', 'item1', (returned1) -> kango.invokeAsync 'kango.storage.getItem', 'item2', (returned2) -> return alert returned1 + returned2 

The result will be the same, although alert returns nothing:

 f = -> alert 'x' return x = f() 

will give undefined to x , but it will:

 f = -> alert 'x' x = f() 
+10
source

In coffeescript, a function always returns the final statement. You can explicitly make the return function undefined by making this the final statement.

 kango.invokeAsync 'kango.storage.getItem', 'item1', (returned1) -> kango.invokeAsync 'kango.storage.getItem', 'item2', (returned2) -> alert returned1 + returned2 `undefined` 
+2
source

All Articles