dsp_099
dsp_099

Reputation: 6121

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?

Upvotes: 5

Views: 2190

Answers (2)

mu is too short
mu is too short

Reputation: 434616

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()

Upvotes: 11

Andrew Hubbs
Andrew Hubbs

Reputation: 9426

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`

Upvotes: 2

Related Questions