Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid this return in nested coffeescript?

Here's 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's 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 is making the function ()-> return something. In that case, the last statement is being returned for some reason.

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

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

How to have it avoid doing the return?

like image 307
dsp_099 Avatar asked Jan 05 '13 23:01

dsp_099


2 Answers

If you don't want a function to return something then 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 don't want any particular return value.

If you don't specify an explicit return value using return, a CoffeeScript function will return the value of the last expression so your CoffeeScript is equivalent to:

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

The result will be the same though, alert doesn't return anything so:

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

will give undefined in x but so will this:

f = -> alert 'x'
x = f()
like image 180
mu is too short Avatar answered Oct 13 '22 11:10

mu is too short


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

kango.invokeAsync 'kango.storage.getItem', 'item1', (returned1) ->

  kango.invokeAsync 'kango.storage.getItem', 'item2', (returned2) ->

    alert returned1 + returned2
    `undefined`
like image 30
Andrew Hubbs Avatar answered Oct 13 '22 12:10

Andrew Hubbs